1//===- Parsing and selection of pass pipelines ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8/// \file
9///
10/// This file provides the implementation of the PassBuilder based on our
11/// static pass registry as well as related functionality. It also provides
12/// helpers to aid in analyzing, debugging, and testing passes and pass
13/// pipelines.
14///
15//===----------------------------------------------------------------------===//
16
17#include "llvm/Passes/PassBuilder.h"
18#include "llvm/ADT/StringSwitch.h"
19#include "llvm/Analysis/AliasAnalysisEvaluator.h"
20#include "llvm/Analysis/AliasSetTracker.h"
21#include "llvm/Analysis/AssumptionCache.h"
22#include "llvm/Analysis/BasicAliasAnalysis.h"
23#include "llvm/Analysis/BlockFrequencyInfo.h"
24#include "llvm/Analysis/BranchProbabilityInfo.h"
25#include "llvm/Analysis/CFGPrinter.h"
26#include "llvm/Analysis/CFLAndersAliasAnalysis.h"
27#include "llvm/Analysis/CFLSteensAliasAnalysis.h"
28#include "llvm/Analysis/CGSCCPassManager.h"
29#include "llvm/Analysis/CallGraph.h"
30#include "llvm/Analysis/CallPrinter.h"
31#include "llvm/Analysis/CostModel.h"
32#include "llvm/Analysis/CycleAnalysis.h"
33#include "llvm/Analysis/DDG.h"
34#include "llvm/Analysis/DDGPrinter.h"
35#include "llvm/Analysis/Delinearization.h"
36#include "llvm/Analysis/DemandedBits.h"
37#include "llvm/Analysis/DependenceAnalysis.h"
38#include "llvm/Analysis/DivergenceAnalysis.h"
39#include "llvm/Analysis/DomPrinter.h"
40#include "llvm/Analysis/DominanceFrontier.h"
41#include "llvm/Analysis/FunctionPropertiesAnalysis.h"
42#include "llvm/Analysis/GlobalsModRef.h"
43#include "llvm/Analysis/IRSimilarityIdentifier.h"
44#include "llvm/Analysis/IVUsers.h"
45#include "llvm/Analysis/InlineAdvisor.h"
46#include "llvm/Analysis/InlineSizeEstimatorAnalysis.h"
47#include "llvm/Analysis/InstCount.h"
48#include "llvm/Analysis/LazyCallGraph.h"
49#include "llvm/Analysis/LazyValueInfo.h"
50#include "llvm/Analysis/Lint.h"
51#include "llvm/Analysis/LoopAccessAnalysis.h"
52#include "llvm/Analysis/LoopCacheAnalysis.h"
53#include "llvm/Analysis/LoopInfo.h"
54#include "llvm/Analysis/LoopNestAnalysis.h"
55#include "llvm/Analysis/MemDerefPrinter.h"
56#include "llvm/Analysis/MemoryDependenceAnalysis.h"
57#include "llvm/Analysis/MemorySSA.h"
58#include "llvm/Analysis/ModuleDebugInfoPrinter.h"
59#include "llvm/Analysis/ModuleSummaryAnalysis.h"
60#include "llvm/Analysis/MustExecute.h"
61#include "llvm/Analysis/ObjCARCAliasAnalysis.h"
62#include "llvm/Analysis/OptimizationRemarkEmitter.h"
63#include "llvm/Analysis/PhiValues.h"
64#include "llvm/Analysis/PostDominators.h"
65#include "llvm/Analysis/ProfileSummaryInfo.h"
66#include "llvm/Analysis/RegionInfo.h"
67#include "llvm/Analysis/ScalarEvolution.h"
68#include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h"
69#include "llvm/Analysis/ScopedNoAliasAA.h"
70#include "llvm/Analysis/StackLifetime.h"
71#include "llvm/Analysis/StackSafetyAnalysis.h"
72#include "llvm/Analysis/TargetLibraryInfo.h"
73#include "llvm/Analysis/TargetTransformInfo.h"
74#include "llvm/Analysis/TypeBasedAliasAnalysis.h"
75#include "llvm/IR/Dominators.h"
76#include "llvm/IR/IRPrintingPasses.h"
77#include "llvm/IR/PassManager.h"
78#include "llvm/IR/PrintPasses.h"
79#include "llvm/IR/SafepointIRVerifier.h"
80#include "llvm/IR/Verifier.h"
81#include "llvm/Support/CommandLine.h"
82#include "llvm/Support/Debug.h"
83#include "llvm/Support/ErrorHandling.h"
84#include "llvm/Support/FormatVariadic.h"
85#include "llvm/Support/Regex.h"
86#include "llvm/Target/TargetMachine.h"
87#include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h"
88#include "llvm/Transforms/Coroutines/CoroCleanup.h"
89#include "llvm/Transforms/Coroutines/CoroEarly.h"
90#include "llvm/Transforms/Coroutines/CoroElide.h"
91#include "llvm/Transforms/Coroutines/CoroSplit.h"
92#include "llvm/Transforms/IPO/AlwaysInliner.h"
93#include "llvm/Transforms/IPO/Annotation2Metadata.h"
94#include "llvm/Transforms/IPO/ArgumentPromotion.h"
95#include "llvm/Transforms/IPO/Attributor.h"
96#include "llvm/Transforms/IPO/BlockExtractor.h"
97#include "llvm/Transforms/IPO/CalledValuePropagation.h"
98#include "llvm/Transforms/IPO/ConstantMerge.h"
99#include "llvm/Transforms/IPO/CrossDSOCFI.h"
100#include "llvm/Transforms/IPO/DeadArgumentElimination.h"
101#include "llvm/Transforms/IPO/ElimAvailExtern.h"
102#include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
103#include "llvm/Transforms/IPO/FunctionAttrs.h"
104#include "llvm/Transforms/IPO/FunctionImport.h"
105#include "llvm/Transforms/IPO/GlobalDCE.h"
106#include "llvm/Transforms/IPO/GlobalOpt.h"
107#include "llvm/Transforms/IPO/GlobalSplit.h"
108#include "llvm/Transforms/IPO/HotColdSplitting.h"
109#include "llvm/Transforms/IPO/IROutliner.h"
110#include "llvm/Transforms/IPO/InferFunctionAttrs.h"
111#include "llvm/Transforms/IPO/Inliner.h"
112#include "llvm/Transforms/IPO/Internalize.h"
113#include "llvm/Transforms/IPO/LoopExtractor.h"
114#include "llvm/Transforms/IPO/LowerTypeTests.h"
115#include "llvm/Transforms/IPO/MergeFunctions.h"
116#include "llvm/Transforms/IPO/ModuleInliner.h"
117#include "llvm/Transforms/IPO/OpenMPOpt.h"
118#include "llvm/Transforms/IPO/PartialInlining.h"
119#include "llvm/Transforms/IPO/SCCP.h"
120#include "llvm/Transforms/IPO/SampleProfile.h"
121#include "llvm/Transforms/IPO/SampleProfileProbe.h"
122#include "llvm/Transforms/IPO/StripDeadPrototypes.h"
123#include "llvm/Transforms/IPO/StripSymbols.h"
124#include "llvm/Transforms/IPO/SyntheticCountsPropagation.h"
125#include "llvm/Transforms/IPO/WholeProgramDevirt.h"
126#include "llvm/Transforms/InstCombine/InstCombine.h"
127#include "llvm/Transforms/Instrumentation.h"
128#include "llvm/Transforms/Instrumentation/AddressSanitizer.h"
129#include "llvm/Transforms/Instrumentation/BoundsChecking.h"
130#include "llvm/Transforms/Instrumentation/CGProfile.h"
131#include "llvm/Transforms/Instrumentation/ControlHeightReduction.h"
132#include "llvm/Transforms/Instrumentation/DataFlowSanitizer.h"
133#include "llvm/Transforms/Instrumentation/GCOVProfiler.h"
134#include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h"
135#include "llvm/Transforms/Instrumentation/InstrOrderFile.h"
136#include "llvm/Transforms/Instrumentation/InstrProfiling.h"
137#include "llvm/Transforms/Instrumentation/MemProfiler.h"
138#include "llvm/Transforms/Instrumentation/MemorySanitizer.h"
139#include "llvm/Transforms/Instrumentation/PGOInstrumentation.h"
140#include "llvm/Transforms/Instrumentation/PoisonChecking.h"
141#include "llvm/Transforms/Instrumentation/SanitizerCoverage.h"
142#include "llvm/Transforms/Instrumentation/ThreadSanitizer.h"
143#include "llvm/Transforms/ObjCARC.h"
144#include "llvm/Transforms/Scalar/ADCE.h"
145#include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
146#include "llvm/Transforms/Scalar/AnnotationRemarks.h"
147#include "llvm/Transforms/Scalar/BDCE.h"
148#include "llvm/Transforms/Scalar/CallSiteSplitting.h"
149#include "llvm/Transforms/Scalar/ConstantHoisting.h"
150#include "llvm/Transforms/Scalar/ConstraintElimination.h"
151#include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
152#include "llvm/Transforms/Scalar/DCE.h"
153#include "llvm/Transforms/Scalar/DFAJumpThreading.h"
154#include "llvm/Transforms/Scalar/DeadStoreElimination.h"
155#include "llvm/Transforms/Scalar/DivRemPairs.h"
156#include "llvm/Transforms/Scalar/EarlyCSE.h"
157#include "llvm/Transforms/Scalar/FlattenCFG.h"
158#include "llvm/Transforms/Scalar/Float2Int.h"
159#include "llvm/Transforms/Scalar/GVN.h"
160#include "llvm/Transforms/Scalar/GuardWidening.h"
161#include "llvm/Transforms/Scalar/IVUsersPrinter.h"
162#include "llvm/Transforms/Scalar/IndVarSimplify.h"
163#include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h"
164#include "llvm/Transforms/Scalar/InferAddressSpaces.h"
165#include "llvm/Transforms/Scalar/InstSimplifyPass.h"
166#include "llvm/Transforms/Scalar/JumpThreading.h"
167#include "llvm/Transforms/Scalar/LICM.h"
168#include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
169#include "llvm/Transforms/Scalar/LoopBoundSplit.h"
170#include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
171#include "llvm/Transforms/Scalar/LoopDeletion.h"
172#include "llvm/Transforms/Scalar/LoopDistribute.h"
173#include "llvm/Transforms/Scalar/LoopFlatten.h"
174#include "llvm/Transforms/Scalar/LoopFuse.h"
175#include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
176#include "llvm/Transforms/Scalar/LoopInstSimplify.h"
177#include "llvm/Transforms/Scalar/LoopInterchange.h"
178#include "llvm/Transforms/Scalar/LoopLoadElimination.h"
179#include "llvm/Transforms/Scalar/LoopPassManager.h"
180#include "llvm/Transforms/Scalar/LoopPredication.h"
181#include "llvm/Transforms/Scalar/LoopReroll.h"
182#include "llvm/Transforms/Scalar/LoopRotation.h"
183#include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
184#include "llvm/Transforms/Scalar/LoopSink.h"
185#include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
186#include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h"
187#include "llvm/Transforms/Scalar/LoopUnrollPass.h"
188#include "llvm/Transforms/Scalar/LoopVersioningLICM.h"
189#include "llvm/Transforms/Scalar/LowerAtomicPass.h"
190#include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
191#include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
192#include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
193#include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h"
194#include "llvm/Transforms/Scalar/LowerWidenableCondition.h"
195#include "llvm/Transforms/Scalar/MakeGuardsExplicit.h"
196#include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
197#include "llvm/Transforms/Scalar/MergeICmps.h"
198#include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
199#include "llvm/Transforms/Scalar/NaryReassociate.h"
200#include "llvm/Transforms/Scalar/NewGVN.h"
201#include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
202#include "llvm/Transforms/Scalar/Reassociate.h"
203#include "llvm/Transforms/Scalar/Reg2Mem.h"
204#include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h"
205#include "llvm/Transforms/Scalar/SCCP.h"
206#include "llvm/Transforms/Scalar/SROA.h"
207#include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
208#include "llvm/Transforms/Scalar/Scalarizer.h"
209#include "llvm/Transforms/Scalar/SeparateConstOffsetFromGEP.h"
210#include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
211#include "llvm/Transforms/Scalar/SimplifyCFG.h"
212#include "llvm/Transforms/Scalar/Sink.h"
213#include "llvm/Transforms/Scalar/SpeculativeExecution.h"
214#include "llvm/Transforms/Scalar/StraightLineStrengthReduce.h"
215#include "llvm/Transforms/Scalar/StructurizeCFG.h"
216#include "llvm/Transforms/Scalar/TLSVariableHoist.h"
217#include "llvm/Transforms/Scalar/TailRecursionElimination.h"
218#include "llvm/Transforms/Scalar/WarnMissedTransforms.h"
219#include "llvm/Transforms/Utils/AddDiscriminators.h"
220#include "llvm/Transforms/Utils/AssumeBundleBuilder.h"
221#include "llvm/Transforms/Utils/BreakCriticalEdges.h"
222#include "llvm/Transforms/Utils/CanonicalizeAliases.h"
223#include "llvm/Transforms/Utils/CanonicalizeFreezeInLoops.h"
224#include "llvm/Transforms/Utils/Debugify.h"
225#include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
226#include "llvm/Transforms/Utils/FixIrreducible.h"
227#include "llvm/Transforms/Utils/HelloWorld.h"
228#include "llvm/Transforms/Utils/InjectTLIMappings.h"
229#include "llvm/Transforms/Utils/InstructionNamer.h"
230#include "llvm/Transforms/Utils/LCSSA.h"
231#include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
232#include "llvm/Transforms/Utils/LoopSimplify.h"
233#include "llvm/Transforms/Utils/LoopVersioning.h"
234#include "llvm/Transforms/Utils/LowerGlobalDtors.h"
235#include "llvm/Transforms/Utils/LowerInvoke.h"
236#include "llvm/Transforms/Utils/LowerSwitch.h"
237#include "llvm/Transforms/Utils/Mem2Reg.h"
238#include "llvm/Transforms/Utils/MetaRenamer.h"
239#include "llvm/Transforms/Utils/NameAnonGlobals.h"
240#include "llvm/Transforms/Utils/PredicateInfo.h"
241#include "llvm/Transforms/Utils/RelLookupTableConverter.h"
242#include "llvm/Transforms/Utils/StripGCRelocates.h"
243#include "llvm/Transforms/Utils/StripNonLineTableDebugInfo.h"
244#include "llvm/Transforms/Utils/SymbolRewriter.h"
245#include "llvm/Transforms/Utils/UnifyFunctionExitNodes.h"
246#include "llvm/Transforms/Utils/UnifyLoopExits.h"
247#include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h"
248#include "llvm/Transforms/Vectorize/LoopVectorize.h"
249#include "llvm/Transforms/Vectorize/SLPVectorizer.h"
250#include "llvm/Transforms/Vectorize/VectorCombine.h"
251
252using namespace llvm;
253
254static const Regex DefaultAliasRegex(
255 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
256
257namespace llvm {
258cl::opt<bool> PrintPipelinePasses(
259 "print-pipeline-passes",
260 cl::desc("Print a '-passes' compatible string describing the pipeline "
261 "(best-effort only)."));
262} // namespace llvm
263
264namespace {
265
266// The following passes/analyses have custom names, otherwise their name will
267// include `(anonymous namespace)`. These are special since they are only for
268// testing purposes and don't live in a header file.
269
270/// No-op module pass which does nothing.
271struct NoOpModulePass : PassInfoMixin<NoOpModulePass> {
272 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
273 return PreservedAnalyses::all();
274 }
275
276 static StringRef name() { return "NoOpModulePass"; }
277};
278
279/// No-op module analysis.
280class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
281 friend AnalysisInfoMixin<NoOpModuleAnalysis>;
282 static AnalysisKey Key;
283
284public:
285 struct Result {};
286 Result run(Module &, ModuleAnalysisManager &) { return Result(); }
287 static StringRef name() { return "NoOpModuleAnalysis"; }
288};
289
290/// No-op CGSCC pass which does nothing.
291struct NoOpCGSCCPass : PassInfoMixin<NoOpCGSCCPass> {
292 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
293 LazyCallGraph &, CGSCCUpdateResult &UR) {
294 return PreservedAnalyses::all();
295 }
296 static StringRef name() { return "NoOpCGSCCPass"; }
297};
298
299/// No-op CGSCC analysis.
300class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
301 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
302 static AnalysisKey Key;
303
304public:
305 struct Result {};
306 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
307 return Result();
308 }
309 static StringRef name() { return "NoOpCGSCCAnalysis"; }
310};
311
312/// No-op function pass which does nothing.
313struct NoOpFunctionPass : PassInfoMixin<NoOpFunctionPass> {
314 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
315 return PreservedAnalyses::all();
316 }
317 static StringRef name() { return "NoOpFunctionPass"; }
318};
319
320/// No-op function analysis.
321class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
322 friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
323 static AnalysisKey Key;
324
325public:
326 struct Result {};
327 Result run(Function &, FunctionAnalysisManager &) { return Result(); }
328 static StringRef name() { return "NoOpFunctionAnalysis"; }
329};
330
331/// No-op loop nest pass which does nothing.
332struct NoOpLoopNestPass : PassInfoMixin<NoOpLoopNestPass> {
333 PreservedAnalyses run(LoopNest &L, LoopAnalysisManager &,
334 LoopStandardAnalysisResults &, LPMUpdater &) {
335 return PreservedAnalyses::all();
336 }
337 static StringRef name() { return "NoOpLoopNestPass"; }
338};
339
340/// No-op loop pass which does nothing.
341struct NoOpLoopPass : PassInfoMixin<NoOpLoopPass> {
342 PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
343 LoopStandardAnalysisResults &, LPMUpdater &) {
344 return PreservedAnalyses::all();
345 }
346 static StringRef name() { return "NoOpLoopPass"; }
347};
348
349/// No-op loop analysis.
350class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
351 friend AnalysisInfoMixin<NoOpLoopAnalysis>;
352 static AnalysisKey Key;
353
354public:
355 struct Result {};
356 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
357 return Result();
358 }
359 static StringRef name() { return "NoOpLoopAnalysis"; }
360};
361
362AnalysisKey NoOpModuleAnalysis::Key;
363AnalysisKey NoOpCGSCCAnalysis::Key;
364AnalysisKey NoOpFunctionAnalysis::Key;
365AnalysisKey NoOpLoopAnalysis::Key;
366
367/// Whether or not we should populate a PassInstrumentationCallbacks's class to
368/// pass name map.
369///
370/// This is for optimization purposes so we don't populate it if we never use
371/// it. This should be updated if new pass instrumentation wants to use the map.
372/// We currently only use this for --print-before/after.
373bool shouldPopulateClassToPassNames() {
374 return PrintPipelinePasses || !printBeforePasses().empty() ||
375 !printAfterPasses().empty();
376}
377
378// A pass for testing -print-on-crash.
379// DO NOT USE THIS EXCEPT FOR TESTING!
380class TriggerCrashPass : public PassInfoMixin<TriggerCrashPass> {
381public:
382 PreservedAnalyses run(Module &, ModuleAnalysisManager &) {
383 abort();
384 return PreservedAnalyses::all();
385 }
386 static StringRef name() { return "TriggerCrashPass"; }
387};
388
389} // namespace
390
391PassBuilder::PassBuilder(TargetMachine *TM, PipelineTuningOptions PTO,
392 Optional<PGOOptions> PGOOpt,
393 PassInstrumentationCallbacks *PIC)
394 : TM(TM), PTO(PTO), PGOOpt(PGOOpt), PIC(PIC) {
395 if (TM)
396 TM->registerPassBuilderCallbacks(*this);
397 if (PIC && shouldPopulateClassToPassNames()) {
398#define MODULE_PASS(NAME, CREATE_PASS) \
399 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
400#define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
401 PIC->addClassToPassName(CLASS, NAME);
402#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
403 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
404#define FUNCTION_PASS(NAME, CREATE_PASS) \
405 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
406#define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
407 PIC->addClassToPassName(CLASS, NAME);
408#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
409 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
410#define LOOPNEST_PASS(NAME, CREATE_PASS) \
411 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
412#define LOOP_PASS(NAME, CREATE_PASS) \
413 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
414#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
415 PIC->addClassToPassName(CLASS, NAME);
416#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
417 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
418#define CGSCC_PASS(NAME, CREATE_PASS) \
419 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
420#define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
421 PIC->addClassToPassName(CLASS, NAME);
422#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
423 PIC->addClassToPassName(decltype(CREATE_PASS)::name(), NAME);
424#include "PassRegistry.def"
425 }
426}
427
428void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
429#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
430 MAM.registerPass([&] { return CREATE_PASS; });
431#include "PassRegistry.def"
432
433 for (auto &C : ModuleAnalysisRegistrationCallbacks)
434 C(MAM);
435}
436
437void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
438#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
439 CGAM.registerPass([&] { return CREATE_PASS; });
440#include "PassRegistry.def"
441
442 for (auto &C : CGSCCAnalysisRegistrationCallbacks)
443 C(CGAM);
444}
445
446void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
447 // We almost always want the default alias analysis pipeline.
448 // If a user wants a different one, they can register their own before calling
449 // registerFunctionAnalyses().
450 FAM.registerPass([&] { return buildDefaultAAPipeline(); });
451
452#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
453 FAM.registerPass([&] { return CREATE_PASS; });
454#include "PassRegistry.def"
455
456 for (auto &C : FunctionAnalysisRegistrationCallbacks)
457 C(FAM);
458}
459
460void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
461#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
462 LAM.registerPass([&] { return CREATE_PASS; });
463#include "PassRegistry.def"
464
465 for (auto &C : LoopAnalysisRegistrationCallbacks)
466 C(LAM);
467}
468
469static Optional<int> parseRepeatPassName(StringRef Name) {
470 if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
471 return None;
472 int Count;
473 if (Name.getAsInteger(0, Count) || Count <= 0)
474 return None;
475 return Count;
476}
477
478static Optional<int> parseDevirtPassName(StringRef Name) {
479 if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
480 return None;
481 int Count;
482 if (Name.getAsInteger(0, Count) || Count < 0)
483 return None;
484 return Count;
485}
486
487static bool checkParametrizedPassName(StringRef Name, StringRef PassName) {
488 if (!Name.consume_front(PassName))
489 return false;
490 // normal pass name w/o parameters == default parameters
491 if (Name.empty())
492 return true;
493 return Name.startswith("<") && Name.endswith(">");
494}
495
496namespace {
497
498/// This performs customized parsing of pass name with parameters.
499///
500/// We do not need parametrization of passes in textual pipeline very often,
501/// yet on a rare occasion ability to specify parameters right there can be
502/// useful.
503///
504/// \p Name - parameterized specification of a pass from a textual pipeline
505/// is a string in a form of :
506/// PassName '<' parameter-list '>'
507///
508/// Parameter list is being parsed by the parser callable argument, \p Parser,
509/// It takes a string-ref of parameters and returns either StringError or a
510/// parameter list in a form of a custom parameters type, all wrapped into
511/// Expected<> template class.
512///
513template <typename ParametersParseCallableT>
514auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name,
515 StringRef PassName) -> decltype(Parser(StringRef{})) {
516 using ParametersT = typename decltype(Parser(StringRef{}))::value_type;
517
518 StringRef Params = Name;
519 if (!Params.consume_front(PassName)) {
520 assert(false &&
521 "unable to strip pass name from parametrized pass specification");
522 }
523 if (!Params.empty() &&
524 (!Params.consume_front("<") || !Params.consume_back(">"))) {
525 assert(false && "invalid format for parametrized pass name");
526 }
527
528 Expected<ParametersT> Result = Parser(Params);
529 assert((Result || Result.template errorIsA<StringError>()) &&
530 "Pass parameter parser can only return StringErrors.");
531 return Result;
532}
533
534/// Parser of parameters for LoopUnroll pass.
535Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) {
536 LoopUnrollOptions UnrollOpts;
537 while (!Params.empty()) {
538 StringRef ParamName;
539 std::tie(ParamName, Params) = Params.split(';');
540 int OptLevel = StringSwitch<int>(ParamName)
541 .Case("O0", 0)
542 .Case("O1", 1)
543 .Case("O2", 2)
544 .Case("O3", 3)
545 .Default(-1);
546 if (OptLevel >= 0) {
547 UnrollOpts.setOptLevel(OptLevel);
548 continue;
549 }
550 if (ParamName.consume_front("full-unroll-max=")) {
551 int Count;
552 if (ParamName.getAsInteger(0, Count))
553 return make_error<StringError>(
554 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
555 inconvertibleErrorCode());
556 UnrollOpts.setFullUnrollMaxCount(Count);
557 continue;
558 }
559
560 bool Enable = !ParamName.consume_front("no-");
561 if (ParamName == "partial") {
562 UnrollOpts.setPartial(Enable);
563 } else if (ParamName == "peeling") {
564 UnrollOpts.setPeeling(Enable);
565 } else if (ParamName == "profile-peeling") {
566 UnrollOpts.setProfileBasedPeeling(Enable);
567 } else if (ParamName == "runtime") {
568 UnrollOpts.setRuntime(Enable);
569 } else if (ParamName == "upperbound") {
570 UnrollOpts.setUpperBound(Enable);
571 } else {
572 return make_error<StringError>(
573 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(),
574 inconvertibleErrorCode());
575 }
576 }
577 return UnrollOpts;
578}
579
580Expected<bool> parseSinglePassOption(StringRef Params, StringRef OptionName,
581 StringRef PassName) {
582 bool Result = false;
583 while (!Params.empty()) {
584 StringRef ParamName;
585 std::tie(ParamName, Params) = Params.split(';');
586
587 if (ParamName == OptionName) {
588 Result = true;
589 } else {
590 return make_error<StringError>(
591 formatv("invalid {1} pass parameter '{0}' ", ParamName, PassName)
592 .str(),
593 inconvertibleErrorCode());
594 }
595 }
596 return Result;
597}
598
599Expected<bool> parseInlinerPassOptions(StringRef Params) {
600 return parseSinglePassOption(Params, "only-mandatory", "InlinerPass");
601}
602
603Expected<bool> parseCoroSplitPassOptions(StringRef Params) {
604 return parseSinglePassOption(Params, "reuse-storage", "CoroSplitPass");
605}
606
607Expected<bool> parseEarlyCSEPassOptions(StringRef Params) {
608 return parseSinglePassOption(Params, "memssa", "EarlyCSE");
609}
610
611Expected<bool> parseEntryExitInstrumenterPassOptions(StringRef Params) {
612 return parseSinglePassOption(Params, "post-inline", "EntryExitInstrumenter");
613}
614
615Expected<bool> parseLoopExtractorPassOptions(StringRef Params) {
616 return parseSinglePassOption(Params, "single", "LoopExtractor");
617}
618
619Expected<bool> parseLowerMatrixIntrinsicsPassOptions(StringRef Params) {
620 return parseSinglePassOption(Params, "minimal", "LowerMatrixIntrinsics");
621}
622
623Expected<AddressSanitizerOptions> parseASanPassOptions(StringRef Params) {
624 AddressSanitizerOptions Result;
625 while (!Params.empty()) {
626 StringRef ParamName;
627 std::tie(ParamName, Params) = Params.split(';');
628
629 if (ParamName == "kernel") {
630 Result.CompileKernel = true;
631 } else {
632 return make_error<StringError>(
633 formatv("invalid AddressSanitizer pass parameter '{0}' ", ParamName)
634 .str(),
635 inconvertibleErrorCode());
636 }
637 }
638 return Result;
639}
640
641Expected<HWAddressSanitizerOptions> parseHWASanPassOptions(StringRef Params) {
642 HWAddressSanitizerOptions Result;
643 while (!Params.empty()) {
644 StringRef ParamName;
645 std::tie(ParamName, Params) = Params.split(';');
646
647 if (ParamName == "recover") {
648 Result.Recover = true;
649 } else if (ParamName == "kernel") {
650 Result.CompileKernel = true;
651 } else {
652 return make_error<StringError>(
653 formatv("invalid HWAddressSanitizer pass parameter '{0}' ", ParamName)
654 .str(),
655 inconvertibleErrorCode());
656 }
657 }
658 return Result;
659}
660
661Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) {
662 MemorySanitizerOptions Result;
663 while (!Params.empty()) {
664 StringRef ParamName;
665 std::tie(ParamName, Params) = Params.split(';');
666
667 if (ParamName == "recover") {
668 Result.Recover = true;
669 } else if (ParamName == "kernel") {
670 Result.Kernel = true;
671 } else if (ParamName.consume_front("track-origins=")) {
672 if (ParamName.getAsInteger(0, Result.TrackOrigins))
673 return make_error<StringError>(
674 formatv("invalid argument to MemorySanitizer pass track-origins "
675 "parameter: '{0}' ",
676 ParamName)
677 .str(),
678 inconvertibleErrorCode());
679 } else if (ParamName == "eager-checks") {
680 Result.EagerChecks = true;
681 } else {
682 return make_error<StringError>(
683 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName)
684 .str(),
685 inconvertibleErrorCode());
686 }
687 }
688 return Result;
689}
690
691/// Parser of parameters for SimplifyCFG pass.
692Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) {
693 SimplifyCFGOptions Result;
694 while (!Params.empty()) {
695 StringRef ParamName;
696 std::tie(ParamName, Params) = Params.split(';');
697
698 bool Enable = !ParamName.consume_front("no-");
699 if (ParamName == "forward-switch-cond") {
700 Result.forwardSwitchCondToPhi(Enable);
701 } else if (ParamName == "switch-range-to-icmp") {
702 Result.convertSwitchRangeToICmp(Enable);
703 } else if (ParamName == "switch-to-lookup") {
704 Result.convertSwitchToLookupTable(Enable);
705 } else if (ParamName == "keep-loops") {
706 Result.needCanonicalLoops(Enable);
707 } else if (ParamName == "hoist-common-insts") {
708 Result.hoistCommonInsts(Enable);
709 } else if (ParamName == "sink-common-insts") {
710 Result.sinkCommonInsts(Enable);
711 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) {
712 APInt BonusInstThreshold;
713 if (ParamName.getAsInteger(0, BonusInstThreshold))
714 return make_error<StringError>(
715 formatv("invalid argument to SimplifyCFG pass bonus-threshold "
716 "parameter: '{0}' ",
717 ParamName).str(),
718 inconvertibleErrorCode());
719 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue());
720 } else {
721 return make_error<StringError>(
722 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(),
723 inconvertibleErrorCode());
724 }
725 }
726 return Result;
727}
728
729/// Parser of parameters for LoopVectorize pass.
730Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) {
731 LoopVectorizeOptions Opts;
732 while (!Params.empty()) {
733 StringRef ParamName;
734 std::tie(ParamName, Params) = Params.split(';');
735
736 bool Enable = !ParamName.consume_front("no-");
737 if (ParamName == "interleave-forced-only") {
738 Opts.setInterleaveOnlyWhenForced(Enable);
739 } else if (ParamName == "vectorize-forced-only") {
740 Opts.setVectorizeOnlyWhenForced(Enable);
741 } else {
742 return make_error<StringError>(
743 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(),
744 inconvertibleErrorCode());
745 }
746 }
747 return Opts;
748}
749
750Expected<std::pair<bool, bool>> parseLoopUnswitchOptions(StringRef Params) {
751 std::pair<bool, bool> Result = {false, true};
752 while (!Params.empty()) {
753 StringRef ParamName;
754 std::tie(ParamName, Params) = Params.split(';');
755
756 bool Enable = !ParamName.consume_front("no-");
757 if (ParamName == "nontrivial") {
758 Result.first = Enable;
759 } else if (ParamName == "trivial") {
760 Result.second = Enable;
761 } else {
762 return make_error<StringError>(
763 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName)
764 .str(),
765 inconvertibleErrorCode());
766 }
767 }
768 return Result;
769}
770
771Expected<LICMOptions> parseLICMOptions(StringRef Params) {
772 LICMOptions Result;
773 while (!Params.empty()) {
774 StringRef ParamName;
775 std::tie(ParamName, Params) = Params.split(';');
776
777 bool Enable = !ParamName.consume_front("no-");
778 if (ParamName == "allowspeculation") {
779 Result.AllowSpeculation = Enable;
780 } else {
781 return make_error<StringError>(
782 formatv("invalid LICM pass parameter '{0}' ", ParamName).str(),
783 inconvertibleErrorCode());
784 }
785 }
786 return Result;
787}
788
789Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) {
790 bool Result = false;
791 while (!Params.empty()) {
792 StringRef ParamName;
793 std::tie(ParamName, Params) = Params.split(';');
794
795 bool Enable = !ParamName.consume_front("no-");
796 if (ParamName == "split-footer-bb") {
797 Result = Enable;
798 } else {
799 return make_error<StringError>(
800 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ",
801 ParamName)
802 .str(),
803 inconvertibleErrorCode());
804 }
805 }
806 return Result;
807}
808
809Expected<GVNOptions> parseGVNOptions(StringRef Params) {
810 GVNOptions Result;
811 while (!Params.empty()) {
812 StringRef ParamName;
813 std::tie(ParamName, Params) = Params.split(';');
814
815 bool Enable = !ParamName.consume_front("no-");
816 if (ParamName == "pre") {
817 Result.setPRE(Enable);
818 } else if (ParamName == "load-pre") {
819 Result.setLoadPRE(Enable);
820 } else if (ParamName == "split-backedge-load-pre") {
821 Result.setLoadPRESplitBackedge(Enable);
822 } else if (ParamName == "memdep") {
823 Result.setMemDep(Enable);
824 } else {
825 return make_error<StringError>(
826 formatv("invalid GVN pass parameter '{0}' ", ParamName).str(),
827 inconvertibleErrorCode());
828 }
829 }
830 return Result;
831}
832
833Expected<StackLifetime::LivenessType>
834parseStackLifetimeOptions(StringRef Params) {
835 StackLifetime::LivenessType Result = StackLifetime::LivenessType::May;
836 while (!Params.empty()) {
837 StringRef ParamName;
838 std::tie(ParamName, Params) = Params.split(';');
839
840 if (ParamName == "may") {
841 Result = StackLifetime::LivenessType::May;
842 } else if (ParamName == "must") {
843 Result = StackLifetime::LivenessType::Must;
844 } else {
845 return make_error<StringError>(
846 formatv("invalid StackLifetime parameter '{0}' ", ParamName).str(),
847 inconvertibleErrorCode());
848 }
849 }
850 return Result;
851}
852
853Expected<bool> parseDependenceAnalysisPrinterOptions(StringRef Params) {
854 return parseSinglePassOption(Params, "normalized-results",
855 "DependenceAnalysisPrinter");
856}
857
858} // namespace
859
860/// Tests whether a pass name starts with a valid prefix for a default pipeline
861/// alias.
862static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
863 return Name.startswith("default") || Name.startswith("thinlto") ||
864 Name.startswith("lto");
865}
866
867/// Tests whether registered callbacks will accept a given pass name.
868///
869/// When parsing a pipeline text, the type of the outermost pipeline may be
870/// omitted, in which case the type is automatically determined from the first
871/// pass name in the text. This may be a name that is handled through one of the
872/// callbacks. We check this through the oridinary parsing callbacks by setting
873/// up a dummy PassManager in order to not force the client to also handle this
874/// type of query.
875template <typename PassManagerT, typename CallbacksT>
876static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) {
877 if (!Callbacks.empty()) {
878 PassManagerT DummyPM;
879 for (auto &CB : Callbacks)
880 if (CB(Name, DummyPM, {}))
881 return true;
882 }
883 return false;
884}
885
886template <typename CallbacksT>
887static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) {
888 // Manually handle aliases for pre-configured pipeline fragments.
889 if (startsWithDefaultPipelineAliasPrefix(Name))
890 return DefaultAliasRegex.match(Name);
891
892 // Explicitly handle pass manager names.
893 if (Name == "module")
894 return true;
895 if (Name == "cgscc")
896 return true;
897 if (Name == "function" || Name == "function<eager-inv>")
898 return true;
899
900 // Explicitly handle custom-parsed pass names.
901 if (parseRepeatPassName(Name))
902 return true;
903
904#define MODULE_PASS(NAME, CREATE_PASS) \
905 if (Name == NAME) \
906 return true;
907#define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
908 if (checkParametrizedPassName(Name, NAME)) \
909 return true;
910#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
911 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
912 return true;
913#include "PassRegistry.def"
914
915 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks);
916}
917
918template <typename CallbacksT>
919static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) {
920 // Explicitly handle pass manager names.
921 if (Name == "cgscc")
922 return true;
923 if (Name == "function" || Name == "function<eager-inv>")
924 return true;
925
926 // Explicitly handle custom-parsed pass names.
927 if (parseRepeatPassName(Name))
928 return true;
929 if (parseDevirtPassName(Name))
930 return true;
931
932#define CGSCC_PASS(NAME, CREATE_PASS) \
933 if (Name == NAME) \
934 return true;
935#define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
936 if (checkParametrizedPassName(Name, NAME)) \
937 return true;
938#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
939 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
940 return true;
941#include "PassRegistry.def"
942
943 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks);
944}
945
946template <typename CallbacksT>
947static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) {
948 // Explicitly handle pass manager names.
949 if (Name == "function" || Name == "function<eager-inv>")
950 return true;
951 if (Name == "loop" || Name == "loop-mssa")
952 return true;
953
954 // Explicitly handle custom-parsed pass names.
955 if (parseRepeatPassName(Name))
956 return true;
957
958#define FUNCTION_PASS(NAME, CREATE_PASS) \
959 if (Name == NAME) \
960 return true;
961#define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
962 if (checkParametrizedPassName(Name, NAME)) \
963 return true;
964#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
965 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
966 return true;
967#include "PassRegistry.def"
968
969 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks);
970}
971
972template <typename CallbacksT>
973static bool isLoopNestPassName(StringRef Name, CallbacksT &Callbacks,
974 bool &UseMemorySSA) {
975 UseMemorySSA = false;
976
977 // Explicitly handle custom-parsed pass names.
978 if (parseRepeatPassName(Name))
979 return true;
980
981 if (Name == "lnicm") {
982 UseMemorySSA = true;
983 return true;
984 }
985
986#define LOOPNEST_PASS(NAME, CREATE_PASS) \
987 if (Name == NAME) \
988 return true;
989#include "PassRegistry.def"
990
991 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
992}
993
994template <typename CallbacksT>
995static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks,
996 bool &UseMemorySSA) {
997 UseMemorySSA = false;
998
999 // Explicitly handle custom-parsed pass names.
1000 if (parseRepeatPassName(Name))
1001 return true;
1002
1003 if (Name == "licm") {
1004 UseMemorySSA = true;
1005 return true;
1006 }
1007
1008#define LOOP_PASS(NAME, CREATE_PASS) \
1009 if (Name == NAME) \
1010 return true;
1011#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1012 if (checkParametrizedPassName(Name, NAME)) \
1013 return true;
1014#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1015 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \
1016 return true;
1017#include "PassRegistry.def"
1018
1019 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks);
1020}
1021
1022Optional<std::vector<PassBuilder::PipelineElement>>
1023PassBuilder::parsePipelineText(StringRef Text) {
1024 std::vector<PipelineElement> ResultPipeline;
1025
1026 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1027 &ResultPipeline};
1028 for (;;) {
1029 std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1030 size_t Pos = Text.find_first_of(",()");
1031 Pipeline.push_back({Text.substr(0, Pos), {}});
1032
1033 // If we have a single terminating name, we're done.
1034 if (Pos == Text.npos)
1035 break;
1036
1037 char Sep = Text[Pos];
1038 Text = Text.substr(Pos + 1);
1039 if (Sep == ',')
1040 // Just a name ending in a comma, continue.
1041 continue;
1042
1043 if (Sep == '(') {
1044 // Push the inner pipeline onto the stack to continue processing.
1045 PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1046 continue;
1047 }
1048
1049 assert(Sep == ')' && "Bogus separator!");
1050 // When handling the close parenthesis, we greedily consume them to avoid
1051 // empty strings in the pipeline.
1052 do {
1053 // If we try to pop the outer pipeline we have unbalanced parentheses.
1054 if (PipelineStack.size() == 1)
1055 return None;
1056
1057 PipelineStack.pop_back();
1058 } while (Text.consume_front(")"));
1059
1060 // Check if we've finished parsing.
1061 if (Text.empty())
1062 break;
1063
1064 // Otherwise, the end of an inner pipeline always has to be followed by
1065 // a comma, and then we can continue.
1066 if (!Text.consume_front(","))
1067 return None;
1068 }
1069
1070 if (PipelineStack.size() > 1)
1071 // Unbalanced paretheses.
1072 return None;
1073
1074 assert(PipelineStack.back() == &ResultPipeline &&
1075 "Wrong pipeline at the bottom of the stack!");
1076 return {std::move(ResultPipeline)};
1077}
1078
1079Error PassBuilder::parseModulePass(ModulePassManager &MPM,
1080 const PipelineElement &E) {
1081 auto &Name = E.Name;
1082 auto &InnerPipeline = E.InnerPipeline;
1083
1084 // First handle complex passes like the pass managers which carry pipelines.
1085 if (!InnerPipeline.empty()) {
1086 if (Name == "module") {
1087 ModulePassManager NestedMPM;
1088 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1089 return Err;
1090 MPM.addPass(std::move(NestedMPM));
1091 return Error::success();
1092 }
1093 if (Name == "cgscc") {
1094 CGSCCPassManager CGPM;
1095 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline))
1096 return Err;
1097 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM)));
1098 return Error::success();
1099 }
1100 if (Name == "function" || Name == "function<eager-inv>") {
1101 FunctionPassManager FPM;
1102 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
1103 return Err;
1104 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM),
1105 Name != "function"));
1106 return Error::success();
1107 }
1108 if (auto Count = parseRepeatPassName(Name)) {
1109 ModulePassManager NestedMPM;
1110 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline))
1111 return Err;
1112 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1113 return Error::success();
1114 }
1115
1116 for (auto &C : ModulePipelineParsingCallbacks)
1117 if (C(Name, MPM, InnerPipeline))
1118 return Error::success();
1119
1120 // Normal passes can't have pipelines.
1121 return make_error<StringError>(
1122 formatv("invalid use of '{0}' pass as module pipeline", Name).str(),
1123 inconvertibleErrorCode());
1124 ;
1125 }
1126
1127 // Manually handle aliases for pre-configured pipeline fragments.
1128 if (startsWithDefaultPipelineAliasPrefix(Name)) {
1129 SmallVector<StringRef, 3> Matches;
1130 if (!DefaultAliasRegex.match(Name, &Matches))
1131 return make_error<StringError>(
1132 formatv("unknown default pipeline alias '{0}'", Name).str(),
1133 inconvertibleErrorCode());
1134
1135 assert(Matches.size() == 3 && "Must capture two matched strings!");
1136
1137 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1138 .Case("O0", OptimizationLevel::O0)
1139 .Case("O1", OptimizationLevel::O1)
1140 .Case("O2", OptimizationLevel::O2)
1141 .Case("O3", OptimizationLevel::O3)
1142 .Case("Os", OptimizationLevel::Os)
1143 .Case("Oz", OptimizationLevel::Oz);
1144 if (L == OptimizationLevel::O0 && Matches[1] != "thinlto" &&
1145 Matches[1] != "lto") {
1146 MPM.addPass(buildO0DefaultPipeline(L, Matches[1] == "thinlto-pre-link" ||
1147 Matches[1] == "lto-pre-link"));
1148 return Error::success();
1149 }
1150
1151 // This is consistent with old pass manager invoked via opt, but
1152 // inconsistent with clang. Clang doesn't enable loop vectorization
1153 // but does enable slp vectorization at Oz.
1154 PTO.LoopVectorization =
1155 L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
1156 PTO.SLPVectorization =
1157 L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz;
1158
1159 if (Matches[1] == "default") {
1160 MPM.addPass(buildPerModuleDefaultPipeline(L));
1161 } else if (Matches[1] == "thinlto-pre-link") {
1162 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L));
1163 } else if (Matches[1] == "thinlto") {
1164 MPM.addPass(buildThinLTODefaultPipeline(L, nullptr));
1165 } else if (Matches[1] == "lto-pre-link") {
1166 MPM.addPass(buildLTOPreLinkDefaultPipeline(L));
1167 } else {
1168 assert(Matches[1] == "lto" && "Not one of the matched options!");
1169 MPM.addPass(buildLTODefaultPipeline(L, nullptr));
1170 }
1171 return Error::success();
1172 }
1173
1174 // Finally expand the basic registered passes from the .inc file.
1175#define MODULE_PASS(NAME, CREATE_PASS) \
1176 if (Name == NAME) { \
1177 MPM.addPass(CREATE_PASS); \
1178 return Error::success(); \
1179 }
1180#define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1181 if (checkParametrizedPassName(Name, NAME)) { \
1182 auto Params = parsePassParameters(PARSER, Name, NAME); \
1183 if (!Params) \
1184 return Params.takeError(); \
1185 MPM.addPass(CREATE_PASS(Params.get())); \
1186 return Error::success(); \
1187 }
1188#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1189 if (Name == "require<" NAME ">") { \
1190 MPM.addPass( \
1191 RequireAnalysisPass< \
1192 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \
1193 return Error::success(); \
1194 } \
1195 if (Name == "invalidate<" NAME ">") { \
1196 MPM.addPass(InvalidateAnalysisPass< \
1197 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1198 return Error::success(); \
1199 }
1200#define CGSCC_PASS(NAME, CREATE_PASS) \
1201 if (Name == NAME) { \
1202 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS)); \
1203 return Error::success(); \
1204 }
1205#define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1206 if (checkParametrizedPassName(Name, NAME)) { \
1207 auto Params = parsePassParameters(PARSER, Name, NAME); \
1208 if (!Params) \
1209 return Params.takeError(); \
1210 MPM.addPass( \
1211 createModuleToPostOrderCGSCCPassAdaptor(CREATE_PASS(Params.get()))); \
1212 return Error::success(); \
1213 }
1214#define FUNCTION_PASS(NAME, CREATE_PASS) \
1215 if (Name == NAME) { \
1216 MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS)); \
1217 return Error::success(); \
1218 }
1219#define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1220 if (checkParametrizedPassName(Name, NAME)) { \
1221 auto Params = parsePassParameters(PARSER, Name, NAME); \
1222 if (!Params) \
1223 return Params.takeError(); \
1224 MPM.addPass(createModuleToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
1225 return Error::success(); \
1226 }
1227#define LOOPNEST_PASS(NAME, CREATE_PASS) \
1228 if (Name == NAME) { \
1229 MPM.addPass(createModuleToFunctionPassAdaptor( \
1230 createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
1231 return Error::success(); \
1232 }
1233#define LOOP_PASS(NAME, CREATE_PASS) \
1234 if (Name == NAME) { \
1235 MPM.addPass(createModuleToFunctionPassAdaptor( \
1236 createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
1237 return Error::success(); \
1238 }
1239#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1240 if (checkParametrizedPassName(Name, NAME)) { \
1241 auto Params = parsePassParameters(PARSER, Name, NAME); \
1242 if (!Params) \
1243 return Params.takeError(); \
1244 MPM.addPass( \
1245 createModuleToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \
1246 CREATE_PASS(Params.get()), false, false))); \
1247 return Error::success(); \
1248 }
1249#include "PassRegistry.def"
1250
1251 for (auto &C : ModulePipelineParsingCallbacks)
1252 if (C(Name, MPM, InnerPipeline))
1253 return Error::success();
1254 return make_error<StringError>(
1255 formatv("unknown module pass '{0}'", Name).str(),
1256 inconvertibleErrorCode());
1257}
1258
1259Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1260 const PipelineElement &E) {
1261 auto &Name = E.Name;
1262 auto &InnerPipeline = E.InnerPipeline;
1263
1264 // First handle complex passes like the pass managers which carry pipelines.
1265 if (!InnerPipeline.empty()) {
1266 if (Name == "cgscc") {
1267 CGSCCPassManager NestedCGPM;
1268 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1269 return Err;
1270 // Add the nested pass manager with the appropriate adaptor.
1271 CGPM.addPass(std::move(NestedCGPM));
1272 return Error::success();
1273 }
1274 if (Name == "function" || Name == "function<eager-inv>") {
1275 FunctionPassManager FPM;
1276 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline))
1277 return Err;
1278 // Add the nested pass manager with the appropriate adaptor.
1279 CGPM.addPass(
1280 createCGSCCToFunctionPassAdaptor(std::move(FPM), Name != "function"));
1281 return Error::success();
1282 }
1283 if (auto Count = parseRepeatPassName(Name)) {
1284 CGSCCPassManager NestedCGPM;
1285 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1286 return Err;
1287 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1288 return Error::success();
1289 }
1290 if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1291 CGSCCPassManager NestedCGPM;
1292 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline))
1293 return Err;
1294 CGPM.addPass(
1295 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions));
1296 return Error::success();
1297 }
1298
1299 for (auto &C : CGSCCPipelineParsingCallbacks)
1300 if (C(Name, CGPM, InnerPipeline))
1301 return Error::success();
1302
1303 // Normal passes can't have pipelines.
1304 return make_error<StringError>(
1305 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(),
1306 inconvertibleErrorCode());
1307 }
1308
1309// Now expand the basic registered passes from the .inc file.
1310#define CGSCC_PASS(NAME, CREATE_PASS) \
1311 if (Name == NAME) { \
1312 CGPM.addPass(CREATE_PASS); \
1313 return Error::success(); \
1314 }
1315#define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1316 if (checkParametrizedPassName(Name, NAME)) { \
1317 auto Params = parsePassParameters(PARSER, Name, NAME); \
1318 if (!Params) \
1319 return Params.takeError(); \
1320 CGPM.addPass(CREATE_PASS(Params.get())); \
1321 return Error::success(); \
1322 }
1323#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1324 if (Name == "require<" NAME ">") { \
1325 CGPM.addPass(RequireAnalysisPass< \
1326 std::remove_reference<decltype(CREATE_PASS)>::type, \
1327 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \
1328 CGSCCUpdateResult &>()); \
1329 return Error::success(); \
1330 } \
1331 if (Name == "invalidate<" NAME ">") { \
1332 CGPM.addPass(InvalidateAnalysisPass< \
1333 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1334 return Error::success(); \
1335 }
1336#define FUNCTION_PASS(NAME, CREATE_PASS) \
1337 if (Name == NAME) { \
1338 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS)); \
1339 return Error::success(); \
1340 }
1341#define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1342 if (checkParametrizedPassName(Name, NAME)) { \
1343 auto Params = parsePassParameters(PARSER, Name, NAME); \
1344 if (!Params) \
1345 return Params.takeError(); \
1346 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CREATE_PASS(Params.get()))); \
1347 return Error::success(); \
1348 }
1349#define LOOPNEST_PASS(NAME, CREATE_PASS) \
1350 if (Name == NAME) { \
1351 CGPM.addPass(createCGSCCToFunctionPassAdaptor( \
1352 createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
1353 return Error::success(); \
1354 }
1355#define LOOP_PASS(NAME, CREATE_PASS) \
1356 if (Name == NAME) { \
1357 CGPM.addPass(createCGSCCToFunctionPassAdaptor( \
1358 createFunctionToLoopPassAdaptor(CREATE_PASS, false, false))); \
1359 return Error::success(); \
1360 }
1361#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1362 if (checkParametrizedPassName(Name, NAME)) { \
1363 auto Params = parsePassParameters(PARSER, Name, NAME); \
1364 if (!Params) \
1365 return Params.takeError(); \
1366 CGPM.addPass( \
1367 createCGSCCToFunctionPassAdaptor(createFunctionToLoopPassAdaptor( \
1368 CREATE_PASS(Params.get()), false, false))); \
1369 return Error::success(); \
1370 }
1371#include "PassRegistry.def"
1372
1373 for (auto &C : CGSCCPipelineParsingCallbacks)
1374 if (C(Name, CGPM, InnerPipeline))
1375 return Error::success();
1376 return make_error<StringError>(
1377 formatv("unknown cgscc pass '{0}'", Name).str(),
1378 inconvertibleErrorCode());
1379}
1380
1381Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1382 const PipelineElement &E) {
1383 auto &Name = E.Name;
1384 auto &InnerPipeline = E.InnerPipeline;
1385
1386 // First handle complex passes like the pass managers which carry pipelines.
1387 if (!InnerPipeline.empty()) {
1388 if (Name == "function") {
1389 FunctionPassManager NestedFPM;
1390 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
1391 return Err;
1392 // Add the nested pass manager with the appropriate adaptor.
1393 FPM.addPass(std::move(NestedFPM));
1394 return Error::success();
1395 }
1396 if (Name == "loop" || Name == "loop-mssa") {
1397 LoopPassManager LPM;
1398 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline))
1399 return Err;
1400 // Add the nested pass manager with the appropriate adaptor.
1401 bool UseMemorySSA = (Name == "loop-mssa");
1402 bool UseBFI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
1403 return Pipeline.Name.contains("licm") ||
1404 Pipeline.Name.contains("simple-loop-unswitch");
1405 });
1406 bool UseBPI = llvm::any_of(InnerPipeline, [](auto Pipeline) {
1407 return Pipeline.Name == "loop-predication";
1408 });
1409 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA,
1410 UseBFI, UseBPI));
1411 return Error::success();
1412 }
1413 if (auto Count = parseRepeatPassName(Name)) {
1414 FunctionPassManager NestedFPM;
1415 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline))
1416 return Err;
1417 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1418 return Error::success();
1419 }
1420
1421 for (auto &C : FunctionPipelineParsingCallbacks)
1422 if (C(Name, FPM, InnerPipeline))
1423 return Error::success();
1424
1425 // Normal passes can't have pipelines.
1426 return make_error<StringError>(
1427 formatv("invalid use of '{0}' pass as function pipeline", Name).str(),
1428 inconvertibleErrorCode());
1429 }
1430
1431// Now expand the basic registered passes from the .inc file.
1432#define FUNCTION_PASS(NAME, CREATE_PASS) \
1433 if (Name == NAME) { \
1434 FPM.addPass(CREATE_PASS); \
1435 return Error::success(); \
1436 }
1437#define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1438 if (checkParametrizedPassName(Name, NAME)) { \
1439 auto Params = parsePassParameters(PARSER, Name, NAME); \
1440 if (!Params) \
1441 return Params.takeError(); \
1442 FPM.addPass(CREATE_PASS(Params.get())); \
1443 return Error::success(); \
1444 }
1445#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1446 if (Name == "require<" NAME ">") { \
1447 FPM.addPass( \
1448 RequireAnalysisPass< \
1449 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \
1450 return Error::success(); \
1451 } \
1452 if (Name == "invalidate<" NAME ">") { \
1453 FPM.addPass(InvalidateAnalysisPass< \
1454 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1455 return Error::success(); \
1456 }
1457// FIXME: UseMemorySSA is set to false. Maybe we could do things like:
1458// bool UseMemorySSA = !("canon-freeze" || "loop-predication" ||
1459// "guard-widening");
1460// The risk is that it may become obsolete if we're not careful.
1461#define LOOPNEST_PASS(NAME, CREATE_PASS) \
1462 if (Name == NAME) { \
1463 FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \
1464 return Error::success(); \
1465 }
1466#define LOOP_PASS(NAME, CREATE_PASS) \
1467 if (Name == NAME) { \
1468 FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS, false, false)); \
1469 return Error::success(); \
1470 }
1471#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1472 if (checkParametrizedPassName(Name, NAME)) { \
1473 auto Params = parsePassParameters(PARSER, Name, NAME); \
1474 if (!Params) \
1475 return Params.takeError(); \
1476 FPM.addPass(createFunctionToLoopPassAdaptor(CREATE_PASS(Params.get()), \
1477 false, false)); \
1478 return Error::success(); \
1479 }
1480#include "PassRegistry.def"
1481
1482 for (auto &C : FunctionPipelineParsingCallbacks)
1483 if (C(Name, FPM, InnerPipeline))
1484 return Error::success();
1485 return make_error<StringError>(
1486 formatv("unknown function pass '{0}'", Name).str(),
1487 inconvertibleErrorCode());
1488}
1489
1490Error PassBuilder::parseLoopPass(LoopPassManager &LPM,
1491 const PipelineElement &E) {
1492 StringRef Name = E.Name;
1493 auto &InnerPipeline = E.InnerPipeline;
1494
1495 // First handle complex passes like the pass managers which carry pipelines.
1496 if (!InnerPipeline.empty()) {
1497 if (Name == "loop") {
1498 LoopPassManager NestedLPM;
1499 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
1500 return Err;
1501 // Add the nested pass manager with the appropriate adaptor.
1502 LPM.addPass(std::move(NestedLPM));
1503 return Error::success();
1504 }
1505 if (auto Count = parseRepeatPassName(Name)) {
1506 LoopPassManager NestedLPM;
1507 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline))
1508 return Err;
1509 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1510 return Error::success();
1511 }
1512
1513 for (auto &C : LoopPipelineParsingCallbacks)
1514 if (C(Name, LPM, InnerPipeline))
1515 return Error::success();
1516
1517 // Normal passes can't have pipelines.
1518 return make_error<StringError>(
1519 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(),
1520 inconvertibleErrorCode());
1521 }
1522
1523// Now expand the basic registered passes from the .inc file.
1524#define LOOPNEST_PASS(NAME, CREATE_PASS) \
1525 if (Name == NAME) { \
1526 LPM.addPass(CREATE_PASS); \
1527 return Error::success(); \
1528 }
1529#define LOOP_PASS(NAME, CREATE_PASS) \
1530 if (Name == NAME) { \
1531 LPM.addPass(CREATE_PASS); \
1532 return Error::success(); \
1533 }
1534#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1535 if (checkParametrizedPassName(Name, NAME)) { \
1536 auto Params = parsePassParameters(PARSER, Name, NAME); \
1537 if (!Params) \
1538 return Params.takeError(); \
1539 LPM.addPass(CREATE_PASS(Params.get())); \
1540 return Error::success(); \
1541 }
1542#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1543 if (Name == "require<" NAME ">") { \
1544 LPM.addPass(RequireAnalysisPass< \
1545 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \
1546 LoopAnalysisManager, LoopStandardAnalysisResults &, \
1547 LPMUpdater &>()); \
1548 return Error::success(); \
1549 } \
1550 if (Name == "invalidate<" NAME ">") { \
1551 LPM.addPass(InvalidateAnalysisPass< \
1552 std::remove_reference<decltype(CREATE_PASS)>::type>()); \
1553 return Error::success(); \
1554 }
1555#include "PassRegistry.def"
1556
1557 for (auto &C : LoopPipelineParsingCallbacks)
1558 if (C(Name, LPM, InnerPipeline))
1559 return Error::success();
1560 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(),
1561 inconvertibleErrorCode());
1562}
1563
1564bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1565#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1566 if (Name == NAME) { \
1567 AA.registerModuleAnalysis< \
1568 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1569 return true; \
1570 }
1571#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1572 if (Name == NAME) { \
1573 AA.registerFunctionAnalysis< \
1574 std::remove_reference<decltype(CREATE_PASS)>::type>(); \
1575 return true; \
1576 }
1577#include "PassRegistry.def"
1578
1579 for (auto &C : AAParsingCallbacks)
1580 if (C(Name, AA))
1581 return true;
1582 return false;
1583}
1584
1585Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1586 ArrayRef<PipelineElement> Pipeline) {
1587 for (const auto &Element : Pipeline) {
1588 if (auto Err = parseLoopPass(LPM, Element))
1589 return Err;
1590 }
1591 return Error::success();
1592}
1593
1594Error PassBuilder::parseFunctionPassPipeline(
1595 FunctionPassManager &FPM, ArrayRef<PipelineElement> Pipeline) {
1596 for (const auto &Element : Pipeline) {
1597 if (auto Err = parseFunctionPass(FPM, Element))
1598 return Err;
1599 }
1600 return Error::success();
1601}
1602
1603Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1604 ArrayRef<PipelineElement> Pipeline) {
1605 for (const auto &Element : Pipeline) {
1606 if (auto Err = parseCGSCCPass(CGPM, Element))
1607 return Err;
1608 }
1609 return Error::success();
1610}
1611
1612void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1613 FunctionAnalysisManager &FAM,
1614 CGSCCAnalysisManager &CGAM,
1615 ModuleAnalysisManager &MAM) {
1616 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1617 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1618 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1619 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1620 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1621 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1622 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1623}
1624
1625Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1626 ArrayRef<PipelineElement> Pipeline) {
1627 for (const auto &Element : Pipeline) {
1628 if (auto Err = parseModulePass(MPM, Element))
1629 return Err;
1630 }
1631 return Error::success();
1632}
1633
1634// Primary pass pipeline description parsing routine for a \c ModulePassManager
1635// FIXME: Should this routine accept a TargetMachine or require the caller to
1636// pre-populate the analysis managers with target-specific stuff?
1637Error PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1638 StringRef PipelineText) {
1639 auto Pipeline = parsePipelineText(PipelineText);
1640 if (!Pipeline || Pipeline->empty())
1641 return make_error<StringError>(
1642 formatv("invalid pipeline '{0}'", PipelineText).str(),
1643 inconvertibleErrorCode());
1644
1645 // If the first name isn't at the module layer, wrap the pipeline up
1646 // automatically.
1647 StringRef FirstName = Pipeline->front().Name;
1648
1649 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) {
1650 bool UseMemorySSA;
1651 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) {
1652 Pipeline = {{"cgscc", std::move(*Pipeline)}};
1653 } else if (isFunctionPassName(FirstName,
1654 FunctionPipelineParsingCallbacks)) {
1655 Pipeline = {{"function", std::move(*Pipeline)}};
1656 } else if (isLoopNestPassName(FirstName, LoopPipelineParsingCallbacks,
1657 UseMemorySSA)) {
1658 Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
1659 std::move(*Pipeline)}}}};
1660 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks,
1661 UseMemorySSA)) {
1662 Pipeline = {{"function", {{UseMemorySSA ? "loop-mssa" : "loop",
1663 std::move(*Pipeline)}}}};
1664 } else {
1665 for (auto &C : TopLevelPipelineParsingCallbacks)
1666 if (C(MPM, *Pipeline))
1667 return Error::success();
1668
1669 // Unknown pass or pipeline name!
1670 auto &InnerPipeline = Pipeline->front().InnerPipeline;
1671 return make_error<StringError>(
1672 formatv("unknown {0} name '{1}'",
1673 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName)
1674 .str(),
1675 inconvertibleErrorCode());
1676 }
1677 }
1678
1679 if (auto Err = parseModulePassPipeline(MPM, *Pipeline))
1680 return Err;
1681 return Error::success();
1682}
1683
1684// Primary pass pipeline description parsing routine for a \c CGSCCPassManager
1685Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM,
1686 StringRef PipelineText) {
1687 auto Pipeline = parsePipelineText(PipelineText);
1688 if (!Pipeline || Pipeline->empty())
1689 return make_error<StringError>(
1690 formatv("invalid pipeline '{0}'", PipelineText).str(),
1691 inconvertibleErrorCode());
1692
1693 StringRef FirstName = Pipeline->front().Name;
1694 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks))
1695 return make_error<StringError>(
1696 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName,
1697 PipelineText)
1698 .str(),
1699 inconvertibleErrorCode());
1700
1701 if (auto Err = parseCGSCCPassPipeline(CGPM, *Pipeline))
1702 return Err;
1703 return Error::success();
1704}
1705
1706// Primary pass pipeline description parsing routine for a \c
1707// FunctionPassManager
1708Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM,
1709 StringRef PipelineText) {
1710 auto Pipeline = parsePipelineText(PipelineText);
1711 if (!Pipeline || Pipeline->empty())
1712 return make_error<StringError>(
1713 formatv("invalid pipeline '{0}'", PipelineText).str(),
1714 inconvertibleErrorCode());
1715
1716 StringRef FirstName = Pipeline->front().Name;
1717 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks))
1718 return make_error<StringError>(
1719 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName,
1720 PipelineText)
1721 .str(),
1722 inconvertibleErrorCode());
1723
1724 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline))
1725 return Err;
1726 return Error::success();
1727}
1728
1729// Primary pass pipeline description parsing routine for a \c LoopPassManager
1730Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM,
1731 StringRef PipelineText) {
1732 auto Pipeline = parsePipelineText(PipelineText);
1733 if (!Pipeline || Pipeline->empty())
1734 return make_error<StringError>(
1735 formatv("invalid pipeline '{0}'", PipelineText).str(),
1736 inconvertibleErrorCode());
1737
1738 if (auto Err = parseLoopPassPipeline(CGPM, *Pipeline))
1739 return Err;
1740
1741 return Error::success();
1742}
1743
1744Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1745 // If the pipeline just consists of the word 'default' just replace the AA
1746 // manager with our default one.
1747 if (PipelineText == "default") {
1748 AA = buildDefaultAAPipeline();
1749 return Error::success();
1750 }
1751
1752 while (!PipelineText.empty()) {
1753 StringRef Name;
1754 std::tie(Name, PipelineText) = PipelineText.split(',');
1755 if (!parseAAPassName(AA, Name))
1756 return make_error<StringError>(
1757 formatv("unknown alias analysis name '{0}'", Name).str(),
1758 inconvertibleErrorCode());
1759 }
1760
1761 return Error::success();
1762}
1763
1764bool PassBuilder::isAAPassName(StringRef PassName) {
1765#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1766 if (PassName == NAME) \
1767 return true;
1768#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1769 if (PassName == NAME) \
1770 return true;
1771#include "PassRegistry.def"
1772 return false;
1773}
1774
1775bool PassBuilder::isAnalysisPassName(StringRef PassName) {
1776#define MODULE_ANALYSIS(NAME, CREATE_PASS) \
1777 if (PassName == NAME) \
1778 return true;
1779#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \
1780 if (PassName == NAME) \
1781 return true;
1782#define LOOP_ANALYSIS(NAME, CREATE_PASS) \
1783 if (PassName == NAME) \
1784 return true;
1785#define CGSCC_ANALYSIS(NAME, CREATE_PASS) \
1786 if (PassName == NAME) \
1787 return true;
1788#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1789 if (PassName == NAME) \
1790 return true;
1791#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \
1792 if (PassName == NAME) \
1793 return true;
1794#include "PassRegistry.def"
1795 return false;
1796}
1797
1798static void printPassName(StringRef PassName, raw_ostream &OS) {
1799 OS << " " << PassName << "\n";
1800}
1801static void printPassName(StringRef PassName, StringRef Params,
1802 raw_ostream &OS) {
1803 OS << " " << PassName << "<" << Params << ">\n";
1804}
1805
1806void PassBuilder::printPassNames(raw_ostream &OS) {
1807 // TODO: print pass descriptions when they are available
1808
1809 OS << "Module passes:\n";
1810#define MODULE_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1811#include "PassRegistry.def"
1812
1813 OS << "Module passes with params:\n";
1814#define MODULE_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1815 printPassName(NAME, PARAMS, OS);
1816#include "PassRegistry.def"
1817
1818 OS << "Module analyses:\n";
1819#define MODULE_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1820#include "PassRegistry.def"
1821
1822 OS << "Module alias analyses:\n";
1823#define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1824#include "PassRegistry.def"
1825
1826 OS << "CGSCC passes:\n";
1827#define CGSCC_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1828#include "PassRegistry.def"
1829
1830 OS << "CGSCC passes with params:\n";
1831#define CGSCC_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1832 printPassName(NAME, PARAMS, OS);
1833#include "PassRegistry.def"
1834
1835 OS << "CGSCC analyses:\n";
1836#define CGSCC_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1837#include "PassRegistry.def"
1838
1839 OS << "Function passes:\n";
1840#define FUNCTION_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1841#include "PassRegistry.def"
1842
1843 OS << "Function passes with params:\n";
1844#define FUNCTION_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1845 printPassName(NAME, PARAMS, OS);
1846#include "PassRegistry.def"
1847
1848 OS << "Function analyses:\n";
1849#define FUNCTION_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1850#include "PassRegistry.def"
1851
1852 OS << "Function alias analyses:\n";
1853#define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1854#include "PassRegistry.def"
1855
1856 OS << "LoopNest passes:\n";
1857#define LOOPNEST_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1858#include "PassRegistry.def"
1859
1860 OS << "Loop passes:\n";
1861#define LOOP_PASS(NAME, CREATE_PASS) printPassName(NAME, OS);
1862#include "PassRegistry.def"
1863
1864 OS << "Loop passes with params:\n";
1865#define LOOP_PASS_WITH_PARAMS(NAME, CLASS, CREATE_PASS, PARSER, PARAMS) \
1866 printPassName(NAME, PARAMS, OS);
1867#include "PassRegistry.def"
1868
1869 OS << "Loop analyses:\n";
1870#define LOOP_ANALYSIS(NAME, CREATE_PASS) printPassName(NAME, OS);
1871#include "PassRegistry.def"
1872}
1873
1874void PassBuilder::registerParseTopLevelPipelineCallback(
1875 const std::function<bool(ModulePassManager &, ArrayRef<PipelineElement>)>
1876 &C) {
1877 TopLevelPipelineParsingCallbacks.push_back(C);
1878}
1879

source code of llvm/lib/Passes/PassBuilder.cpp