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