OSDN Git Service

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