]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/lib/Passes/PassBuilder.cpp
Merge ^/head r319548 through r319778.
[FreeBSD/FreeBSD.git] / contrib / llvm / lib / Passes / PassBuilder.cpp
1 //===- Parsing, selection, and construction of pass pipelines -------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 /// \file
10 ///
11 /// This file provides the implementation of the PassBuilder based on our
12 /// static pass registry as well as related functionality. It also provides
13 /// helpers to aid in analyzing, debugging, and testing passes and pass
14 /// pipelines.
15 ///
16 //===----------------------------------------------------------------------===//
17
18 #include "llvm/Passes/PassBuilder.h"
19 #include "llvm/ADT/StringSwitch.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/AliasAnalysisEvaluator.h"
22 #include "llvm/Analysis/AssumptionCache.h"
23 #include "llvm/Analysis/BasicAliasAnalysis.h"
24 #include "llvm/Analysis/BlockFrequencyInfo.h"
25 #include "llvm/Analysis/BlockFrequencyInfoImpl.h"
26 #include "llvm/Analysis/BranchProbabilityInfo.h"
27 #include "llvm/Analysis/CFGPrinter.h"
28 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
29 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
30 #include "llvm/Analysis/CGSCCPassManager.h"
31 #include "llvm/Analysis/CallGraph.h"
32 #include "llvm/Analysis/DemandedBits.h"
33 #include "llvm/Analysis/DependenceAnalysis.h"
34 #include "llvm/Analysis/DominanceFrontier.h"
35 #include "llvm/Analysis/GlobalsModRef.h"
36 #include "llvm/Analysis/IVUsers.h"
37 #include "llvm/Analysis/LazyCallGraph.h"
38 #include "llvm/Analysis/LazyValueInfo.h"
39 #include "llvm/Analysis/LoopAccessAnalysis.h"
40 #include "llvm/Analysis/LoopInfo.h"
41 #include "llvm/Analysis/MemoryDependenceAnalysis.h"
42 #include "llvm/Analysis/MemorySSA.h"
43 #include "llvm/Analysis/ModuleSummaryAnalysis.h"
44 #include "llvm/Analysis/OptimizationDiagnosticInfo.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/TargetLibraryInfo.h"
52 #include "llvm/Analysis/TargetTransformInfo.h"
53 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
54 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
55 #include "llvm/CodeGen/UnreachableBlockElim.h"
56 #include "llvm/IR/Dominators.h"
57 #include "llvm/IR/IRPrintingPasses.h"
58 #include "llvm/IR/PassManager.h"
59 #include "llvm/IR/Verifier.h"
60 #include "llvm/Support/Debug.h"
61 #include "llvm/Support/Regex.h"
62 #include "llvm/Target/TargetMachine.h"
63 #include "llvm/Transforms/GCOVProfiler.h"
64 #include "llvm/Transforms/IPO/AlwaysInliner.h"
65 #include "llvm/Transforms/IPO/ArgumentPromotion.h"
66 #include "llvm/Transforms/IPO/ConstantMerge.h"
67 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
68 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
69 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
70 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
71 #include "llvm/Transforms/IPO/FunctionAttrs.h"
72 #include "llvm/Transforms/IPO/FunctionImport.h"
73 #include "llvm/Transforms/IPO/GlobalDCE.h"
74 #include "llvm/Transforms/IPO/GlobalOpt.h"
75 #include "llvm/Transforms/IPO/GlobalSplit.h"
76 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
77 #include "llvm/Transforms/IPO/Inliner.h"
78 #include "llvm/Transforms/IPO/Internalize.h"
79 #include "llvm/Transforms/IPO/LowerTypeTests.h"
80 #include "llvm/Transforms/IPO/PartialInlining.h"
81 #include "llvm/Transforms/IPO/SCCP.h"
82 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
83 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
84 #include "llvm/Transforms/InstCombine/InstCombine.h"
85 #include "llvm/Transforms/InstrProfiling.h"
86 #include "llvm/Transforms/PGOInstrumentation.h"
87 #include "llvm/Transforms/SampleProfile.h"
88 #include "llvm/Transforms/Scalar/ADCE.h"
89 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
90 #include "llvm/Transforms/Scalar/BDCE.h"
91 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
92 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
93 #include "llvm/Transforms/Scalar/DCE.h"
94 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
95 #include "llvm/Transforms/Scalar/EarlyCSE.h"
96 #include "llvm/Transforms/Scalar/Float2Int.h"
97 #include "llvm/Transforms/Scalar/GVN.h"
98 #include "llvm/Transforms/Scalar/GuardWidening.h"
99 #include "llvm/Transforms/Scalar/IVUsersPrinter.h"
100 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
101 #include "llvm/Transforms/Scalar/JumpThreading.h"
102 #include "llvm/Transforms/Scalar/LICM.h"
103 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h"
104 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
105 #include "llvm/Transforms/Scalar/LoopDeletion.h"
106 #include "llvm/Transforms/Scalar/LoopDistribute.h"
107 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
108 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
109 #include "llvm/Transforms/Scalar/LoopLoadElimination.h"
110 #include "llvm/Transforms/Scalar/LoopPassManager.h"
111 #include "llvm/Transforms/Scalar/LoopPredication.h"
112 #include "llvm/Transforms/Scalar/LoopRotation.h"
113 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
114 #include "llvm/Transforms/Scalar/LoopSink.h"
115 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
116 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
117 #include "llvm/Transforms/Scalar/LowerAtomic.h"
118 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
119 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
120 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
121 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
122 #include "llvm/Transforms/Scalar/NaryReassociate.h"
123 #include "llvm/Transforms/Scalar/NewGVN.h"
124 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
125 #include "llvm/Transforms/Scalar/Reassociate.h"
126 #include "llvm/Transforms/Scalar/SCCP.h"
127 #include "llvm/Transforms/Scalar/SROA.h"
128 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h"
129 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
130 #include "llvm/Transforms/Scalar/Sink.h"
131 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
132 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
133 #include "llvm/Transforms/Utils/AddDiscriminators.h"
134 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
135 #include "llvm/Transforms/Utils/LCSSA.h"
136 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h"
137 #include "llvm/Transforms/Utils/LoopSimplify.h"
138 #include "llvm/Transforms/Utils/LowerInvoke.h"
139 #include "llvm/Transforms/Utils/Mem2Reg.h"
140 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
141 #include "llvm/Transforms/Utils/PredicateInfo.h"
142 #include "llvm/Transforms/Utils/SimplifyInstructions.h"
143 #include "llvm/Transforms/Utils/SymbolRewriter.h"
144 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
145 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
146
147 #include <type_traits>
148
149 using namespace llvm;
150
151 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations",
152                                              cl::ReallyHidden, cl::init(4));
153 static cl::opt<bool>
154     RunPartialInlining("enable-npm-partial-inlining", cl::init(false),
155                        cl::Hidden, cl::ZeroOrMore,
156                        cl::desc("Run Partial inlinining pass"));
157
158 static cl::opt<bool>
159     RunNewGVN("enable-npm-newgvn", cl::init(false),
160               cl::Hidden, cl::ZeroOrMore,
161               cl::desc("Run NewGVN instead of GVN"));
162
163 static cl::opt<bool> EnableGVNHoist(
164     "enable-npm-gvn-hoist", cl::init(false), cl::Hidden,
165     cl::desc("Enable the GVN hoisting pass for the new PM (default = off)"));
166
167 static Regex DefaultAliasRegex(
168     "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$");
169
170 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) {
171   switch (Level) {
172   case PassBuilder::O0:
173   case PassBuilder::O1:
174   case PassBuilder::O2:
175   case PassBuilder::O3:
176     return false;
177
178   case PassBuilder::Os:
179   case PassBuilder::Oz:
180     return true;
181   }
182   llvm_unreachable("Invalid optimization level!");
183 }
184
185 namespace {
186
187 /// \brief No-op module pass which does nothing.
188 struct NoOpModulePass {
189   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
190     return PreservedAnalyses::all();
191   }
192   static StringRef name() { return "NoOpModulePass"; }
193 };
194
195 /// \brief No-op module analysis.
196 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
197   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
198   static AnalysisKey Key;
199
200 public:
201   struct Result {};
202   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
203   static StringRef name() { return "NoOpModuleAnalysis"; }
204 };
205
206 /// \brief No-op CGSCC pass which does nothing.
207 struct NoOpCGSCCPass {
208   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
209                         LazyCallGraph &, CGSCCUpdateResult &UR) {
210     return PreservedAnalyses::all();
211   }
212   static StringRef name() { return "NoOpCGSCCPass"; }
213 };
214
215 /// \brief No-op CGSCC analysis.
216 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
217   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
218   static AnalysisKey Key;
219
220 public:
221   struct Result {};
222   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
223     return Result();
224   }
225   static StringRef name() { return "NoOpCGSCCAnalysis"; }
226 };
227
228 /// \brief No-op function pass which does nothing.
229 struct NoOpFunctionPass {
230   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
231     return PreservedAnalyses::all();
232   }
233   static StringRef name() { return "NoOpFunctionPass"; }
234 };
235
236 /// \brief No-op function analysis.
237 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
238   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
239   static AnalysisKey Key;
240
241 public:
242   struct Result {};
243   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
244   static StringRef name() { return "NoOpFunctionAnalysis"; }
245 };
246
247 /// \brief No-op loop pass which does nothing.
248 struct NoOpLoopPass {
249   PreservedAnalyses run(Loop &L, LoopAnalysisManager &,
250                         LoopStandardAnalysisResults &, LPMUpdater &) {
251     return PreservedAnalyses::all();
252   }
253   static StringRef name() { return "NoOpLoopPass"; }
254 };
255
256 /// \brief No-op loop analysis.
257 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
258   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
259   static AnalysisKey Key;
260
261 public:
262   struct Result {};
263   Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) {
264     return Result();
265   }
266   static StringRef name() { return "NoOpLoopAnalysis"; }
267 };
268
269 AnalysisKey NoOpModuleAnalysis::Key;
270 AnalysisKey NoOpCGSCCAnalysis::Key;
271 AnalysisKey NoOpFunctionAnalysis::Key;
272 AnalysisKey NoOpLoopAnalysis::Key;
273
274 } // End anonymous namespace.
275
276 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
277 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
278   MAM.registerPass([&] { return CREATE_PASS; });
279 #include "PassRegistry.def"
280 }
281
282 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
283 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
284   CGAM.registerPass([&] { return CREATE_PASS; });
285 #include "PassRegistry.def"
286 }
287
288 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
289 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
290   FAM.registerPass([&] { return CREATE_PASS; });
291 #include "PassRegistry.def"
292 }
293
294 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
295 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
296   LAM.registerPass([&] { return CREATE_PASS; });
297 #include "PassRegistry.def"
298 }
299
300 FunctionPassManager
301 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level,
302                                                  bool DebugLogging) {
303   assert(Level != O0 && "Must request optimizations!");
304   FunctionPassManager FPM(DebugLogging);
305
306   // Form SSA out of local memory accesses after breaking apart aggregates into
307   // scalars.
308   FPM.addPass(SROA());
309
310   // Catch trivial redundancies
311   FPM.addPass(EarlyCSEPass());
312
313   // Hoisting of scalars and load expressions.
314   if (EnableGVNHoist)
315     FPM.addPass(GVNHoistPass());
316
317   // Speculative execution if the target has divergent branches; otherwise nop.
318   FPM.addPass(SpeculativeExecutionPass());
319
320   // Optimize based on known information about branches, and cleanup afterward.
321   FPM.addPass(JumpThreadingPass());
322   FPM.addPass(CorrelatedValuePropagationPass());
323   FPM.addPass(SimplifyCFGPass());
324   FPM.addPass(InstCombinePass());
325
326   if (!isOptimizingForSize(Level))
327     FPM.addPass(LibCallsShrinkWrapPass());
328
329   FPM.addPass(TailCallElimPass());
330   FPM.addPass(SimplifyCFGPass());
331
332   // Form canonically associated expression trees, and simplify the trees using
333   // basic mathematical properties. For example, this will form (nearly)
334   // minimal multiplication trees.
335   FPM.addPass(ReassociatePass());
336
337   // Add the primary loop simplification pipeline.
338   // FIXME: Currently this is split into two loop pass pipelines because we run
339   // some function passes in between them. These can and should be replaced by
340   // loop pass equivalenst but those aren't ready yet. Specifically,
341   // `SimplifyCFGPass` and `InstCombinePass` are used. We have
342   // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to
343   // the other we have is `LoopInstSimplify`.
344   LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging);
345
346   // Rotate Loop - disable header duplication at -Oz
347   LPM1.addPass(LoopRotatePass(Level != Oz));
348   LPM1.addPass(LICMPass());
349   LPM1.addPass(SimpleLoopUnswitchPass());
350   LPM2.addPass(IndVarSimplifyPass());
351   LPM2.addPass(LoopIdiomRecognizePass());
352   LPM2.addPass(LoopDeletionPass());
353   // FIXME: The old pass manager has a hack to disable loop unrolling during
354   // ThinLTO when using sample PGO. Need to either fix it or port some
355   // workaround.
356   LPM2.addPass(LoopUnrollPass::createFull(Level));
357
358   // We provide the opt remark emitter pass for LICM to use. We only need to do
359   // this once as it is immutable.
360   FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
361   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1)));
362   FPM.addPass(SimplifyCFGPass());
363   FPM.addPass(InstCombinePass());
364   FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2)));
365
366   // Eliminate redundancies.
367   if (Level != O1) {
368     // These passes add substantial compile time so skip them at O1.
369     FPM.addPass(MergedLoadStoreMotionPass());
370     if (RunNewGVN)
371       FPM.addPass(NewGVNPass());
372     else
373       FPM.addPass(GVN());
374   }
375
376   // Specially optimize memory movement as it doesn't look like dataflow in SSA.
377   FPM.addPass(MemCpyOptPass());
378
379   // Sparse conditional constant propagation.
380   // FIXME: It isn't clear why we do this *after* loop passes rather than
381   // before...
382   FPM.addPass(SCCPPass());
383
384   // Delete dead bit computations (instcombine runs after to fold away the dead
385   // computations, and then ADCE will run later to exploit any new DCE
386   // opportunities that creates).
387   FPM.addPass(BDCEPass());
388
389   // Run instcombine after redundancy and dead bit elimination to exploit
390   // opportunities opened up by them.
391   FPM.addPass(InstCombinePass());
392
393   // Re-consider control flow based optimizations after redundancy elimination,
394   // redo DCE, etc.
395   FPM.addPass(JumpThreadingPass());
396   FPM.addPass(CorrelatedValuePropagationPass());
397   FPM.addPass(DSEPass());
398   FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
399
400   // Finally, do an expensive DCE pass to catch all the dead code exposed by
401   // the simplifications and basic cleanup after all the simplifications.
402   FPM.addPass(ADCEPass());
403   FPM.addPass(SimplifyCFGPass());
404   FPM.addPass(InstCombinePass());
405
406   return FPM;
407 }
408
409 static void addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging,
410                               PassBuilder::OptimizationLevel Level,
411                               bool RunProfileGen, std::string ProfileGenFile,
412                               std::string ProfileUseFile) {
413   // Generally running simplification passes and the inliner with an high
414   // threshold results in smaller executables, but there may be cases where
415   // the size grows, so let's be conservative here and skip this simplification
416   // at -Os/Oz.
417   if (!isOptimizingForSize(Level)) {
418     InlineParams IP;
419
420     // In the old pass manager, this is a cl::opt. Should still this be one?
421     IP.DefaultThreshold = 75;
422
423     // FIXME: The hint threshold has the same value used by the regular inliner.
424     // This should probably be lowered after performance testing.
425     // FIXME: this comment is cargo culted from the old pass manager, revisit).
426     IP.HintThreshold = 325;
427
428     CGSCCPassManager CGPipeline(DebugLogging);
429
430     CGPipeline.addPass(InlinerPass(IP));
431
432     FunctionPassManager FPM;
433     FPM.addPass(SROA());
434     FPM.addPass(EarlyCSEPass());    // Catch trivial redundancies.
435     FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks.
436     FPM.addPass(InstCombinePass()); // Combine silly sequences.
437
438     // FIXME: Here the old pass manager inserts peephole extensions.
439     // Add them when they're supported.
440     CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM)));
441
442     MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline)));
443   }
444
445   // Delete anything that is now dead to make sure that we don't instrument
446   // dead code. Instrumentation can end up keeping dead code around and
447   // dramatically increase code size.
448   MPM.addPass(GlobalDCEPass());
449
450   if (RunProfileGen) {
451     MPM.addPass(PGOInstrumentationGen());
452
453     // Add the profile lowering pass.
454     InstrProfOptions Options;
455     if (!ProfileGenFile.empty())
456       Options.InstrProfileOutput = ProfileGenFile;
457     MPM.addPass(InstrProfiling(Options));
458   }
459
460   if (!ProfileUseFile.empty())
461     MPM.addPass(PGOInstrumentationUse(ProfileUseFile));
462 }
463
464 ModulePassManager
465 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level,
466                                                bool DebugLogging) {
467   ModulePassManager MPM(DebugLogging);
468
469   // Do basic inference of function attributes from known properties of system
470   // libraries and other oracles.
471   MPM.addPass(InferFunctionAttrsPass());
472
473   // Create an early function pass manager to cleanup the output of the
474   // frontend.
475   FunctionPassManager EarlyFPM(DebugLogging);
476   EarlyFPM.addPass(SimplifyCFGPass());
477   EarlyFPM.addPass(SROA());
478   EarlyFPM.addPass(EarlyCSEPass());
479   EarlyFPM.addPass(LowerExpectIntrinsicPass());
480   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
481
482   // Interprocedural constant propagation now that basic cleanup has occured
483   // and prior to optimizing globals.
484   // FIXME: This position in the pipeline hasn't been carefully considered in
485   // years, it should be re-analyzed.
486   MPM.addPass(IPSCCPPass());
487
488   // Optimize globals to try and fold them into constants.
489   MPM.addPass(GlobalOptPass());
490
491   // Promote any localized globals to SSA registers.
492   // FIXME: Should this instead by a run of SROA?
493   // FIXME: We should probably run instcombine and simplify-cfg afterward to
494   // delete control flows that are dead once globals have been folded to
495   // constants.
496   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
497
498   // Remove any dead arguments exposed by cleanups and constand folding
499   // globals.
500   MPM.addPass(DeadArgumentEliminationPass());
501
502   // Create a small function pass pipeline to cleanup after all the global
503   // optimizations.
504   FunctionPassManager GlobalCleanupPM(DebugLogging);
505   GlobalCleanupPM.addPass(InstCombinePass());
506   GlobalCleanupPM.addPass(SimplifyCFGPass());
507   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM)));
508
509   // Add all the requested passes for PGO, if requested.
510   if (PGOOpt) {
511     assert(PGOOpt->RunProfileGen || PGOOpt->SamplePGO ||
512            !PGOOpt->ProfileUseFile.empty());
513     addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen,
514                       PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile);
515
516     // Indirect call promotion that promotes intra-module targes only.
517     MPM.addPass(PGOIndirectCallPromotion(false, PGOOpt && PGOOpt->SamplePGO));
518   }
519
520   // Require the GlobalsAA analysis for the module so we can query it within
521   // the CGSCC pipeline.
522   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
523
524   // Require the ProfileSummaryAnalysis for the module so we can query it within
525   // the inliner pass.
526   MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>());
527
528   // Now begin the main postorder CGSCC pipeline.
529   // FIXME: The current CGSCC pipeline has its origins in the legacy pass
530   // manager and trying to emulate its precise behavior. Much of this doesn't
531   // make a lot of sense and we should revisit the core CGSCC structure.
532   CGSCCPassManager MainCGPipeline(DebugLogging);
533
534   // Note: historically, the PruneEH pass was run first to deduce nounwind and
535   // generally clean up exception handling overhead. It isn't clear this is
536   // valuable as the inliner doesn't currently care whether it is inlining an
537   // invoke or a call.
538
539   // Run the inliner first. The theory is that we are walking bottom-up and so
540   // the callees have already been fully optimized, and we want to inline them
541   // into the callers so that our optimizations can reflect that.
542   // FIXME; Customize the threshold based on optimization level.
543   MainCGPipeline.addPass(InlinerPass());
544
545   // Now deduce any function attributes based in the current code.
546   MainCGPipeline.addPass(PostOrderFunctionAttrsPass());
547
548   // When at O3 add argument promotion to the pass pipeline.
549   // FIXME: It isn't at all clear why this should be limited to O3.
550   if (Level == O3)
551     MainCGPipeline.addPass(ArgumentPromotionPass());
552
553   // Lastly, add the core function simplification pipeline nested inside the
554   // CGSCC walk.
555   MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor(
556       buildFunctionSimplificationPipeline(Level, DebugLogging)));
557
558   // We wrap the CGSCC pipeline in a devirtualization repeater. This will try
559   // to detect when we devirtualize indirect calls and iterate the SCC passes
560   // in that case to try and catch knock-on inlining or function attrs
561   // opportunities. Then we add it to the module pipeline by walking the SCCs
562   // in postorder (or bottom-up).
563   MPM.addPass(
564       createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass(
565           std::move(MainCGPipeline), MaxDevirtIterations, DebugLogging)));
566
567   return MPM;
568 }
569
570 ModulePassManager
571 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level,
572                                              bool DebugLogging) {
573   ModulePassManager MPM(DebugLogging);
574
575   // Optimize globals now that the module is fully simplified.
576   MPM.addPass(GlobalOptPass());
577
578   // Run partial inlining pass to partially inline functions that have
579   // large bodies.
580   if (RunPartialInlining)
581     MPM.addPass(PartialInlinerPass());
582
583   // Remove avail extern fns and globals definitions since we aren't compiling
584   // an object file for later LTO. For LTO we want to preserve these so they
585   // are eligible for inlining at link-time. Note if they are unreferenced they
586   // will be removed by GlobalDCE later, so this only impacts referenced
587   // available externally globals. Eventually they will be suppressed during
588   // codegen, but eliminating here enables more opportunity for GlobalDCE as it
589   // may make globals referenced by available external functions dead and saves
590   // running remaining passes on the eliminated functions.
591   MPM.addPass(EliminateAvailableExternallyPass());
592
593   // Do RPO function attribute inference across the module to forward-propagate
594   // attributes where applicable.
595   // FIXME: Is this really an optimization rather than a canonicalization?
596   MPM.addPass(ReversePostOrderFunctionAttrsPass());
597
598   // Re-require GloblasAA here prior to function passes. This is particularly
599   // useful as the above will have inlined, DCE'ed, and function-attr
600   // propagated everything. We should at this point have a reasonably minimal
601   // and richly annotated call graph. By computing aliasing and mod/ref
602   // information for all local globals here, the late loop passes and notably
603   // the vectorizer will be able to use them to help recognize vectorizable
604   // memory operations.
605   MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>());
606
607   FunctionPassManager OptimizePM(DebugLogging);
608   OptimizePM.addPass(Float2IntPass());
609   // FIXME: We need to run some loop optimizations to re-rotate loops after
610   // simplify-cfg and others undo their rotation.
611
612   // Optimize the loop execution. These passes operate on entire loop nests
613   // rather than on each loop in an inside-out manner, and so they are actually
614   // function passes.
615
616   // First rotate loops that may have been un-rotated by prior passes.
617   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass()));
618
619   // Distribute loops to allow partial vectorization.  I.e. isolate dependences
620   // into separate loop that would otherwise inhibit vectorization.  This is
621   // currently only performed for loops marked with the metadata
622   // llvm.loop.distribute=true or when -enable-loop-distribute is specified.
623   OptimizePM.addPass(LoopDistributePass());
624
625   // Now run the core loop vectorizer.
626   OptimizePM.addPass(LoopVectorizePass());
627
628   // Eliminate loads by forwarding stores from the previous iteration to loads
629   // of the current iteration.
630   OptimizePM.addPass(LoopLoadEliminationPass());
631
632   // Cleanup after the loop optimization passes.
633   OptimizePM.addPass(InstCombinePass());
634
635
636   // Now that we've formed fast to execute loop structures, we do further
637   // optimizations. These are run afterward as they might block doing complex
638   // analyses and transforms such as what are needed for loop vectorization.
639
640   // Optimize parallel scalar instruction chains into SIMD instructions.
641   OptimizePM.addPass(SLPVectorizerPass());
642
643   // Cleanup after all of the vectorizers.
644   OptimizePM.addPass(SimplifyCFGPass());
645   OptimizePM.addPass(InstCombinePass());
646
647   // Unroll small loops to hide loop backedge latency and saturate any parallel
648   // execution resources of an out-of-order processor. We also then need to
649   // clean up redundancies and loop invariant code.
650   // FIXME: It would be really good to use a loop-integrated instruction
651   // combiner for cleanup here so that the unrolling and LICM can be pipelined
652   // across the loop nests.
653   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopUnrollPass::create(Level)));
654   OptimizePM.addPass(InstCombinePass());
655   OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>());
656   OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass()));
657
658   // Now that we've vectorized and unrolled loops, we may have more refined
659   // alignment information, try to re-derive it here.
660   OptimizePM.addPass(AlignmentFromAssumptionsPass());
661
662   // LoopSink pass sinks instructions hoisted by LICM, which serves as a
663   // canonicalization pass that enables other optimizations. As a result,
664   // LoopSink pass needs to be a very late IR pass to avoid undoing LICM
665   // result too early.
666   OptimizePM.addPass(LoopSinkPass());
667
668   // And finally clean up LCSSA form before generating code.
669   OptimizePM.addPass(InstSimplifierPass());
670
671   // LoopSink (and other loop passes since the last simplifyCFG) might have
672   // resulted in single-entry-single-exit or empty blocks. Clean up the CFG.
673   OptimizePM.addPass(SimplifyCFGPass());
674
675   // Add the core optimizing pipeline.
676   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM)));
677
678   // Now we need to do some global optimization transforms.
679   // FIXME: It would seem like these should come first in the optimization
680   // pipeline and maybe be the bottom of the canonicalization pipeline? Weird
681   // ordering here.
682   MPM.addPass(GlobalDCEPass());
683   MPM.addPass(ConstantMergePass());
684
685   return MPM;
686 }
687
688 ModulePassManager
689 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level,
690                                            bool DebugLogging) {
691   assert(Level != O0 && "Must request optimizations for the default pipeline!");
692
693   ModulePassManager MPM(DebugLogging);
694
695   // Force any function attributes we want the rest of the pipeline to observe.
696   MPM.addPass(ForceFunctionAttrsPass());
697
698   // Add the core simplification pipeline.
699   MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
700
701   // Now add the optimization pipeline.
702   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
703
704   return MPM;
705 }
706
707 ModulePassManager
708 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level,
709                                                 bool DebugLogging) {
710   assert(Level != O0 && "Must request optimizations for the default pipeline!");
711
712   ModulePassManager MPM(DebugLogging);
713
714   // Force any function attributes we want the rest of the pipeline to observe.
715   MPM.addPass(ForceFunctionAttrsPass());
716
717   // If we are planning to perform ThinLTO later, we don't bloat the code with
718   // unrolling/vectorization/... now. Just simplify the module as much as we
719   // can.
720   MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
721
722   // Run partial inlining pass to partially inline functions that have
723   // large bodies.
724   // FIXME: It isn't clear whether this is really the right place to run this
725   // in ThinLTO. Because there is another canonicalization and simplification
726   // phase that will run after the thin link, running this here ends up with
727   // less information than will be available later and it may grow functions in
728   // ways that aren't beneficial.
729   if (RunPartialInlining)
730     MPM.addPass(PartialInlinerPass());
731
732   // Reduce the size of the IR as much as possible.
733   MPM.addPass(GlobalOptPass());
734
735   // Rename anon globals to be able to export them in the summary.
736   MPM.addPass(NameAnonGlobalPass());
737
738   return MPM;
739 }
740
741 ModulePassManager
742 PassBuilder::buildThinLTODefaultPipeline(OptimizationLevel Level,
743                                          bool DebugLogging) {
744   // FIXME: The summary index is not hooked in the new pass manager yet.
745   // When it's going to be hooked, enable WholeProgramDevirt and LowerTypeTest
746   // here.
747
748   ModulePassManager MPM(DebugLogging);
749
750   // Force any function attributes we want the rest of the pipeline to observe.
751   MPM.addPass(ForceFunctionAttrsPass());
752
753   // During the ThinLTO backend phase we perform early indirect call promotion
754   // here, before globalopt. Otherwise imported available_externally functions
755   // look unreferenced and are removed.
756   MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
757                                        PGOOpt && PGOOpt->SamplePGO &&
758                                            !PGOOpt->ProfileUseFile.empty()));
759
760   // Add the core simplification pipeline.
761   MPM.addPass(buildModuleSimplificationPipeline(Level, DebugLogging));
762
763   // Now add the optimization pipeline.
764   MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging));
765
766   return MPM;
767 }
768
769 ModulePassManager
770 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level,
771                                             bool DebugLogging) {
772   assert(Level != O0 && "Must request optimizations for the default pipeline!");
773   // FIXME: We should use a customized pre-link pipeline!
774   return buildPerModuleDefaultPipeline(Level, DebugLogging);
775 }
776
777 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level,
778                                                        bool DebugLogging) {
779   assert(Level != O0 && "Must request optimizations for the default pipeline!");
780   ModulePassManager MPM(DebugLogging);
781
782   // Remove unused virtual tables to improve the quality of code generated by
783   // whole-program devirtualization and bitset lowering.
784   MPM.addPass(GlobalDCEPass());
785
786   // Force any function attributes we want the rest of the pipeline to observe.
787   MPM.addPass(ForceFunctionAttrsPass());
788
789   // Do basic inference of function attributes from known properties of system
790   // libraries and other oracles.
791   MPM.addPass(InferFunctionAttrsPass());
792
793   if (Level > 1) {
794     // Indirect call promotion. This should promote all the targets that are
795     // left by the earlier promotion pass that promotes intra-module targets.
796     // This two-step promotion is to save the compile time. For LTO, it should
797     // produce the same result as if we only do promotion here.
798     MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */,
799                                          PGOOpt && PGOOpt->SamplePGO));
800
801     // Propagate constants at call sites into the functions they call.  This
802     // opens opportunities for globalopt (and inlining) by substituting function
803     // pointers passed as arguments to direct uses of functions.
804    MPM.addPass(IPSCCPPass());
805   }
806
807   // Now deduce any function attributes based in the current code.
808   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
809               PostOrderFunctionAttrsPass()));
810
811   // Do RPO function attribute inference across the module to forward-propagate
812   // attributes where applicable.
813   // FIXME: Is this really an optimization rather than a canonicalization?
814   MPM.addPass(ReversePostOrderFunctionAttrsPass());
815
816   // Use inragne annotations on GEP indices to split globals where beneficial.
817   MPM.addPass(GlobalSplitPass());
818
819   // Run whole program optimization of virtual call when the list of callees
820   // is fixed.
821   MPM.addPass(WholeProgramDevirtPass());
822
823   // Stop here at -O1.
824   if (Level == 1)
825     return MPM;
826
827   // Optimize globals to try and fold them into constants.
828   MPM.addPass(GlobalOptPass());
829
830   // Promote any localized globals to SSA registers.
831   MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass()));
832
833   // Linking modules together can lead to duplicate global constant, only
834   // keep one copy of each constant.
835   MPM.addPass(ConstantMergePass());
836
837   // Remove unused arguments from functions.
838   MPM.addPass(DeadArgumentEliminationPass());
839
840   // Reduce the code after globalopt and ipsccp.  Both can open up significant
841   // simplification opportunities, and both can propagate functions through
842   // function pointers.  When this happens, we often have to resolve varargs
843   // calls, etc, so let instcombine do this.
844   // FIXME: add peephole extensions here as the legacy PM does.
845   MPM.addPass(createModuleToFunctionPassAdaptor(InstCombinePass()));
846
847   // Note: historically, the PruneEH pass was run first to deduce nounwind and
848   // generally clean up exception handling overhead. It isn't clear this is
849   // valuable as the inliner doesn't currently care whether it is inlining an
850   // invoke or a call.
851   // Run the inliner now.
852   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(InlinerPass()));
853
854   // Optimize globals again after we ran the inliner.
855   MPM.addPass(GlobalOptPass());
856
857   // Garbage collect dead functions.
858   // FIXME: Add ArgumentPromotion pass after once it's ported.
859   MPM.addPass(GlobalDCEPass());
860
861   FunctionPassManager FPM(DebugLogging);
862
863   // The IPO Passes may leave cruft around. Clean up after them.
864   // FIXME: add peephole extensions here as the legacy PM does.
865   FPM.addPass(InstCombinePass());
866   FPM.addPass(JumpThreadingPass());
867
868   // Break up allocas
869   FPM.addPass(SROA());
870
871   // Run a few AA driver optimizations here and now to cleanup the code.
872   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
873
874   MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(
875               PostOrderFunctionAttrsPass()));
876   // FIXME: here we run IP alias analysis in the legacy PM.
877
878   FunctionPassManager MainFPM;
879
880   // FIXME: once we fix LoopPass Manager, add LICM here.
881   // FIXME: once we provide support for enabling MLSM, add it here.
882   // FIXME: once we provide support for enabling NewGVN, add it here.
883   if (RunNewGVN)
884     MainFPM.addPass(NewGVNPass());
885   else
886     MainFPM.addPass(GVN());
887
888   // Remove dead memcpy()'s.
889   MainFPM.addPass(MemCpyOptPass());
890
891   // Nuke dead stores.
892   MainFPM.addPass(DSEPass());
893
894   // FIXME: at this point, we run a bunch of loop passes:
895   // indVarSimplify, loopDeletion, loopInterchange, loopUnrool,
896   // loopVectorize. Enable them once the remaining issue with LPM
897   // are sorted out.
898
899   MainFPM.addPass(InstCombinePass());
900   MainFPM.addPass(SimplifyCFGPass());
901   MainFPM.addPass(SCCPPass());
902   MainFPM.addPass(InstCombinePass());
903   MainFPM.addPass(BDCEPass());
904
905   // FIXME: We may want to run SLPVectorizer here.
906   // After vectorization, assume intrinsics may tell us more
907   // about pointer alignments.
908 #if 0
909   MainFPM.add(AlignmentFromAssumptionsPass());
910 #endif
911
912   // FIXME: Conditionally run LoadCombine here, after it's ported
913   // (in case we still have this pass, given its questionable usefulness).
914
915   // FIXME: add peephole extensions to the PM here.
916   MainFPM.addPass(InstCombinePass());
917   MainFPM.addPass(JumpThreadingPass());
918   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM)));
919
920   // Create a function that performs CFI checks for cross-DSO calls with
921   // targets in the current module.
922   MPM.addPass(CrossDSOCFIPass());
923
924   // Lower type metadata and the type.test intrinsic. This pass supports
925   // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs
926   // to be run at link time if CFI is enabled. This pass does nothing if
927   // CFI is disabled.
928   // Enable once we add support for the summary in the new PM.
929 #if 0
930   MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export :
931                                            PassSummaryAction::None,
932                                 Summary));
933 #endif
934
935   // Add late LTO optimization passes.
936   // Delete basic blocks, which optimization passes may have killed.
937   MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass()));
938
939   // Drop bodies of available eternally objects to improve GlobalDCE.
940   MPM.addPass(EliminateAvailableExternallyPass());
941
942   // Now that we have optimized the program, discard unreachable functions.
943   MPM.addPass(GlobalDCEPass());
944
945   // FIXME: Enable MergeFuncs, conditionally, after ported, maybe.
946   return MPM;
947 }
948
949 AAManager PassBuilder::buildDefaultAAPipeline() {
950   AAManager AA;
951
952   // The order in which these are registered determines their priority when
953   // being queried.
954
955   // First we register the basic alias analysis that provides the majority of
956   // per-function local AA logic. This is a stateless, on-demand local set of
957   // AA techniques.
958   AA.registerFunctionAnalysis<BasicAA>();
959
960   // Next we query fast, specialized alias analyses that wrap IR-embedded
961   // information about aliasing.
962   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
963   AA.registerFunctionAnalysis<TypeBasedAA>();
964
965   // Add support for querying global aliasing information when available.
966   // Because the `AAManager` is a function analysis and `GlobalsAA` is a module
967   // analysis, all that the `AAManager` can do is query for any *cached*
968   // results from `GlobalsAA` through a readonly proxy.
969   AA.registerModuleAnalysis<GlobalsAA>();
970
971   return AA;
972 }
973
974 static Optional<int> parseRepeatPassName(StringRef Name) {
975   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
976     return None;
977   int Count;
978   if (Name.getAsInteger(0, Count) || Count <= 0)
979     return None;
980   return Count;
981 }
982
983 static Optional<int> parseDevirtPassName(StringRef Name) {
984   if (!Name.consume_front("devirt<") || !Name.consume_back(">"))
985     return None;
986   int Count;
987   if (Name.getAsInteger(0, Count) || Count <= 0)
988     return None;
989   return Count;
990 }
991
992 /// Tests whether a pass name starts with a valid prefix for a default pipeline
993 /// alias.
994 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) {
995   return Name.startswith("default") || Name.startswith("thinlto") ||
996          Name.startswith("lto");
997 }
998
999 static bool isModulePassName(StringRef Name) {
1000   // Manually handle aliases for pre-configured pipeline fragments.
1001   if (startsWithDefaultPipelineAliasPrefix(Name))
1002     return DefaultAliasRegex.match(Name);
1003
1004   // Explicitly handle pass manager names.
1005   if (Name == "module")
1006     return true;
1007   if (Name == "cgscc")
1008     return true;
1009   if (Name == "function")
1010     return true;
1011
1012   // Explicitly handle custom-parsed pass names.
1013   if (parseRepeatPassName(Name))
1014     return true;
1015
1016 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1017   if (Name == NAME)                                                            \
1018     return true;
1019 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1020   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1021     return true;
1022 #include "PassRegistry.def"
1023
1024   return false;
1025 }
1026
1027 static bool isCGSCCPassName(StringRef Name) {
1028   // Explicitly handle pass manager names.
1029   if (Name == "cgscc")
1030     return true;
1031   if (Name == "function")
1032     return true;
1033
1034   // Explicitly handle custom-parsed pass names.
1035   if (parseRepeatPassName(Name))
1036     return true;
1037   if (parseDevirtPassName(Name))
1038     return true;
1039
1040 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1041   if (Name == NAME)                                                            \
1042     return true;
1043 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1044   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1045     return true;
1046 #include "PassRegistry.def"
1047
1048   return false;
1049 }
1050
1051 static bool isFunctionPassName(StringRef Name) {
1052   // Explicitly handle pass manager names.
1053   if (Name == "function")
1054     return true;
1055   if (Name == "loop")
1056     return true;
1057
1058   // Explicitly handle custom-parsed pass names.
1059   if (parseRepeatPassName(Name))
1060     return true;
1061
1062 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1063   if (Name == NAME)                                                            \
1064     return true;
1065 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1066   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1067     return true;
1068 #include "PassRegistry.def"
1069
1070   return false;
1071 }
1072
1073 static bool isLoopPassName(StringRef Name) {
1074   // Explicitly handle pass manager names.
1075   if (Name == "loop")
1076     return true;
1077
1078   // Explicitly handle custom-parsed pass names.
1079   if (parseRepeatPassName(Name))
1080     return true;
1081
1082 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1083   if (Name == NAME)                                                            \
1084     return true;
1085 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1086   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
1087     return true;
1088 #include "PassRegistry.def"
1089
1090   return false;
1091 }
1092
1093 Optional<std::vector<PassBuilder::PipelineElement>>
1094 PassBuilder::parsePipelineText(StringRef Text) {
1095   std::vector<PipelineElement> ResultPipeline;
1096
1097   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
1098       &ResultPipeline};
1099   for (;;) {
1100     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
1101     size_t Pos = Text.find_first_of(",()");
1102     Pipeline.push_back({Text.substr(0, Pos), {}});
1103
1104     // If we have a single terminating name, we're done.
1105     if (Pos == Text.npos)
1106       break;
1107
1108     char Sep = Text[Pos];
1109     Text = Text.substr(Pos + 1);
1110     if (Sep == ',')
1111       // Just a name ending in a comma, continue.
1112       continue;
1113
1114     if (Sep == '(') {
1115       // Push the inner pipeline onto the stack to continue processing.
1116       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
1117       continue;
1118     }
1119
1120     assert(Sep == ')' && "Bogus separator!");
1121     // When handling the close parenthesis, we greedily consume them to avoid
1122     // empty strings in the pipeline.
1123     do {
1124       // If we try to pop the outer pipeline we have unbalanced parentheses.
1125       if (PipelineStack.size() == 1)
1126         return None;
1127
1128       PipelineStack.pop_back();
1129     } while (Text.consume_front(")"));
1130
1131     // Check if we've finished parsing.
1132     if (Text.empty())
1133       break;
1134
1135     // Otherwise, the end of an inner pipeline always has to be followed by
1136     // a comma, and then we can continue.
1137     if (!Text.consume_front(","))
1138       return None;
1139   }
1140
1141   if (PipelineStack.size() > 1)
1142     // Unbalanced paretheses.
1143     return None;
1144
1145   assert(PipelineStack.back() == &ResultPipeline &&
1146          "Wrong pipeline at the bottom of the stack!");
1147   return {std::move(ResultPipeline)};
1148 }
1149
1150 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
1151                                   const PipelineElement &E, bool VerifyEachPass,
1152                                   bool DebugLogging) {
1153   auto &Name = E.Name;
1154   auto &InnerPipeline = E.InnerPipeline;
1155
1156   // First handle complex passes like the pass managers which carry pipelines.
1157   if (!InnerPipeline.empty()) {
1158     if (Name == "module") {
1159       ModulePassManager NestedMPM(DebugLogging);
1160       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1161                                    DebugLogging))
1162         return false;
1163       MPM.addPass(std::move(NestedMPM));
1164       return true;
1165     }
1166     if (Name == "cgscc") {
1167       CGSCCPassManager CGPM(DebugLogging);
1168       if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
1169                                   DebugLogging))
1170         return false;
1171       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM),
1172                                                           DebugLogging));
1173       return true;
1174     }
1175     if (Name == "function") {
1176       FunctionPassManager FPM(DebugLogging);
1177       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1178                                      DebugLogging))
1179         return false;
1180       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
1181       return true;
1182     }
1183     if (auto Count = parseRepeatPassName(Name)) {
1184       ModulePassManager NestedMPM(DebugLogging);
1185       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
1186                                    DebugLogging))
1187         return false;
1188       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
1189       return true;
1190     }
1191     // Normal passes can't have pipelines.
1192     return false;
1193   }
1194
1195   // Manually handle aliases for pre-configured pipeline fragments.
1196   if (startsWithDefaultPipelineAliasPrefix(Name)) {
1197     SmallVector<StringRef, 3> Matches;
1198     if (!DefaultAliasRegex.match(Name, &Matches))
1199       return false;
1200     assert(Matches.size() == 3 && "Must capture two matched strings!");
1201
1202     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
1203         .Case("O0", O0)
1204         .Case("O1", O1)
1205         .Case("O2", O2)
1206         .Case("O3", O3)
1207         .Case("Os", Os)
1208         .Case("Oz", Oz);
1209     if (L == O0)
1210       // At O0 we do nothing at all!
1211       return true;
1212
1213     if (Matches[1] == "default") {
1214       MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging));
1215     } else if (Matches[1] == "thinlto-pre-link") {
1216       MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging));
1217     } else if (Matches[1] == "thinlto") {
1218       MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging));
1219     } else if (Matches[1] == "lto-pre-link") {
1220       MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging));
1221     } else {
1222       assert(Matches[1] == "lto" && "Not one of the matched options!");
1223       MPM.addPass(buildLTODefaultPipeline(L, DebugLogging));
1224     }
1225     return true;
1226   }
1227
1228   // Finally expand the basic registered passes from the .inc file.
1229 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
1230   if (Name == NAME) {                                                          \
1231     MPM.addPass(CREATE_PASS);                                                  \
1232     return true;                                                               \
1233   }
1234 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
1235   if (Name == "require<" NAME ">") {                                           \
1236     MPM.addPass(                                                               \
1237         RequireAnalysisPass<                                                   \
1238             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
1239     return true;                                                               \
1240   }                                                                            \
1241   if (Name == "invalidate<" NAME ">") {                                        \
1242     MPM.addPass(InvalidateAnalysisPass<                                        \
1243                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1244     return true;                                                               \
1245   }
1246 #include "PassRegistry.def"
1247
1248   return false;
1249 }
1250
1251 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
1252                                  const PipelineElement &E, bool VerifyEachPass,
1253                                  bool DebugLogging) {
1254   auto &Name = E.Name;
1255   auto &InnerPipeline = E.InnerPipeline;
1256
1257   // First handle complex passes like the pass managers which carry pipelines.
1258   if (!InnerPipeline.empty()) {
1259     if (Name == "cgscc") {
1260       CGSCCPassManager NestedCGPM(DebugLogging);
1261       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1262                                   DebugLogging))
1263         return false;
1264       // Add the nested pass manager with the appropriate adaptor.
1265       CGPM.addPass(std::move(NestedCGPM));
1266       return true;
1267     }
1268     if (Name == "function") {
1269       FunctionPassManager FPM(DebugLogging);
1270       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
1271                                      DebugLogging))
1272         return false;
1273       // Add the nested pass manager with the appropriate adaptor.
1274       CGPM.addPass(
1275           createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging));
1276       return true;
1277     }
1278     if (auto Count = parseRepeatPassName(Name)) {
1279       CGSCCPassManager NestedCGPM(DebugLogging);
1280       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1281                                   DebugLogging))
1282         return false;
1283       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
1284       return true;
1285     }
1286     if (auto MaxRepetitions = parseDevirtPassName(Name)) {
1287       CGSCCPassManager NestedCGPM(DebugLogging);
1288       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
1289                                   DebugLogging))
1290         return false;
1291       CGPM.addPass(createDevirtSCCRepeatedPass(std::move(NestedCGPM),
1292                                                *MaxRepetitions, DebugLogging));
1293       return true;
1294     }
1295     // Normal passes can't have pipelines.
1296     return false;
1297   }
1298
1299   // Now expand the basic registered passes from the .inc file.
1300 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
1301   if (Name == NAME) {                                                          \
1302     CGPM.addPass(CREATE_PASS);                                                 \
1303     return true;                                                               \
1304   }
1305 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
1306   if (Name == "require<" NAME ">") {                                           \
1307     CGPM.addPass(RequireAnalysisPass<                                          \
1308                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
1309                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
1310                  CGSCCUpdateResult &>());                                      \
1311     return true;                                                               \
1312   }                                                                            \
1313   if (Name == "invalidate<" NAME ">") {                                        \
1314     CGPM.addPass(InvalidateAnalysisPass<                                       \
1315                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
1316     return true;                                                               \
1317   }
1318 #include "PassRegistry.def"
1319
1320   return false;
1321 }
1322
1323 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
1324                                     const PipelineElement &E,
1325                                     bool VerifyEachPass, bool DebugLogging) {
1326   auto &Name = E.Name;
1327   auto &InnerPipeline = E.InnerPipeline;
1328
1329   // First handle complex passes like the pass managers which carry pipelines.
1330   if (!InnerPipeline.empty()) {
1331     if (Name == "function") {
1332       FunctionPassManager NestedFPM(DebugLogging);
1333       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1334                                      DebugLogging))
1335         return false;
1336       // Add the nested pass manager with the appropriate adaptor.
1337       FPM.addPass(std::move(NestedFPM));
1338       return true;
1339     }
1340     if (Name == "loop") {
1341       LoopPassManager LPM(DebugLogging);
1342       if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
1343                                  DebugLogging))
1344         return false;
1345       // Add the nested pass manager with the appropriate adaptor.
1346       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
1347       return true;
1348     }
1349     if (auto Count = parseRepeatPassName(Name)) {
1350       FunctionPassManager NestedFPM(DebugLogging);
1351       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
1352                                      DebugLogging))
1353         return false;
1354       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
1355       return true;
1356     }
1357     // Normal passes can't have pipelines.
1358     return false;
1359   }
1360
1361   // Now expand the basic registered passes from the .inc file.
1362 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
1363   if (Name == NAME) {                                                          \
1364     FPM.addPass(CREATE_PASS);                                                  \
1365     return true;                                                               \
1366   }
1367 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
1368   if (Name == "require<" NAME ">") {                                           \
1369     FPM.addPass(                                                               \
1370         RequireAnalysisPass<                                                   \
1371             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
1372     return true;                                                               \
1373   }                                                                            \
1374   if (Name == "invalidate<" NAME ">") {                                        \
1375     FPM.addPass(InvalidateAnalysisPass<                                        \
1376                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1377     return true;                                                               \
1378   }
1379 #include "PassRegistry.def"
1380
1381   return false;
1382 }
1383
1384 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
1385                                 bool VerifyEachPass, bool DebugLogging) {
1386   StringRef Name = E.Name;
1387   auto &InnerPipeline = E.InnerPipeline;
1388
1389   // First handle complex passes like the pass managers which carry pipelines.
1390   if (!InnerPipeline.empty()) {
1391     if (Name == "loop") {
1392       LoopPassManager NestedLPM(DebugLogging);
1393       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1394                                  DebugLogging))
1395         return false;
1396       // Add the nested pass manager with the appropriate adaptor.
1397       LPM.addPass(std::move(NestedLPM));
1398       return true;
1399     }
1400     if (auto Count = parseRepeatPassName(Name)) {
1401       LoopPassManager NestedLPM(DebugLogging);
1402       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
1403                                  DebugLogging))
1404         return false;
1405       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
1406       return true;
1407     }
1408     // Normal passes can't have pipelines.
1409     return false;
1410   }
1411
1412   // Now expand the basic registered passes from the .inc file.
1413 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
1414   if (Name == NAME) {                                                          \
1415     LPM.addPass(CREATE_PASS);                                                  \
1416     return true;                                                               \
1417   }
1418 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
1419   if (Name == "require<" NAME ">") {                                           \
1420     LPM.addPass(RequireAnalysisPass<                                           \
1421                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop,      \
1422                 LoopAnalysisManager, LoopStandardAnalysisResults &,            \
1423                 LPMUpdater &>());                                              \
1424     return true;                                                               \
1425   }                                                                            \
1426   if (Name == "invalidate<" NAME ">") {                                        \
1427     LPM.addPass(InvalidateAnalysisPass<                                        \
1428                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
1429     return true;                                                               \
1430   }
1431 #include "PassRegistry.def"
1432
1433   return false;
1434 }
1435
1436 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
1437 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
1438   if (Name == NAME) {                                                          \
1439     AA.registerModuleAnalysis<                                                 \
1440         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1441     return true;                                                               \
1442   }
1443 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
1444   if (Name == NAME) {                                                          \
1445     AA.registerFunctionAnalysis<                                               \
1446         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
1447     return true;                                                               \
1448   }
1449 #include "PassRegistry.def"
1450
1451   return false;
1452 }
1453
1454 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
1455                                         ArrayRef<PipelineElement> Pipeline,
1456                                         bool VerifyEachPass,
1457                                         bool DebugLogging) {
1458   for (const auto &Element : Pipeline) {
1459     if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
1460       return false;
1461     // FIXME: No verifier support for Loop passes!
1462   }
1463   return true;
1464 }
1465
1466 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
1467                                             ArrayRef<PipelineElement> Pipeline,
1468                                             bool VerifyEachPass,
1469                                             bool DebugLogging) {
1470   for (const auto &Element : Pipeline) {
1471     if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
1472       return false;
1473     if (VerifyEachPass)
1474       FPM.addPass(VerifierPass());
1475   }
1476   return true;
1477 }
1478
1479 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
1480                                          ArrayRef<PipelineElement> Pipeline,
1481                                          bool VerifyEachPass,
1482                                          bool DebugLogging) {
1483   for (const auto &Element : Pipeline) {
1484     if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
1485       return false;
1486     // FIXME: No verifier support for CGSCC passes!
1487   }
1488   return true;
1489 }
1490
1491 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
1492                                        FunctionAnalysisManager &FAM,
1493                                        CGSCCAnalysisManager &CGAM,
1494                                        ModuleAnalysisManager &MAM) {
1495   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
1496   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
1497   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
1498   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
1499   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
1500   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
1501   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
1502 }
1503
1504 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
1505                                           ArrayRef<PipelineElement> Pipeline,
1506                                           bool VerifyEachPass,
1507                                           bool DebugLogging) {
1508   for (const auto &Element : Pipeline) {
1509     if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
1510       return false;
1511     if (VerifyEachPass)
1512       MPM.addPass(VerifierPass());
1513   }
1514   return true;
1515 }
1516
1517 // Primary pass pipeline description parsing routine.
1518 // FIXME: Should this routine accept a TargetMachine or require the caller to
1519 // pre-populate the analysis managers with target-specific stuff?
1520 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
1521                                     StringRef PipelineText, bool VerifyEachPass,
1522                                     bool DebugLogging) {
1523   auto Pipeline = parsePipelineText(PipelineText);
1524   if (!Pipeline || Pipeline->empty())
1525     return false;
1526
1527   // If the first name isn't at the module layer, wrap the pipeline up
1528   // automatically.
1529   StringRef FirstName = Pipeline->front().Name;
1530
1531   if (!isModulePassName(FirstName)) {
1532     if (isCGSCCPassName(FirstName))
1533       Pipeline = {{"cgscc", std::move(*Pipeline)}};
1534     else if (isFunctionPassName(FirstName))
1535       Pipeline = {{"function", std::move(*Pipeline)}};
1536     else if (isLoopPassName(FirstName))
1537       Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
1538     else
1539       // Unknown pass name!
1540       return false;
1541   }
1542
1543   return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
1544 }
1545
1546 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
1547   // If the pipeline just consists of the word 'default' just replace the AA
1548   // manager with our default one.
1549   if (PipelineText == "default") {
1550     AA = buildDefaultAAPipeline();
1551     return true;
1552   }
1553
1554   while (!PipelineText.empty()) {
1555     StringRef Name;
1556     std::tie(Name, PipelineText) = PipelineText.split(',');
1557     if (!parseAAPassName(AA, Name))
1558       return false;
1559   }
1560
1561   return true;
1562 }