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/ModuleSummaryAnalysis.h"
43 #include "llvm/Analysis/OptimizationDiagnosticInfo.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/GCOVProfiler.h"
63 #include "llvm/Transforms/IPO/AlwaysInliner.h"
64 #include "llvm/Transforms/IPO/ConstantMerge.h"
65 #include "llvm/Transforms/IPO/CrossDSOCFI.h"
66 #include "llvm/Transforms/IPO/DeadArgumentElimination.h"
67 #include "llvm/Transforms/IPO/ElimAvailExtern.h"
68 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h"
69 #include "llvm/Transforms/IPO/FunctionAttrs.h"
70 #include "llvm/Transforms/IPO/FunctionImport.h"
71 #include "llvm/Transforms/IPO/GlobalDCE.h"
72 #include "llvm/Transforms/IPO/GlobalOpt.h"
73 #include "llvm/Transforms/IPO/InferFunctionAttrs.h"
74 #include "llvm/Transforms/IPO/Internalize.h"
75 #include "llvm/Transforms/IPO/LowerTypeTests.h"
76 #include "llvm/Transforms/IPO/PartialInlining.h"
77 #include "llvm/Transforms/IPO/SCCP.h"
78 #include "llvm/Transforms/IPO/StripDeadPrototypes.h"
79 #include "llvm/Transforms/IPO/WholeProgramDevirt.h"
80 #include "llvm/Transforms/InstCombine/InstCombine.h"
81 #include "llvm/Transforms/InstrProfiling.h"
82 #include "llvm/Transforms/PGOInstrumentation.h"
83 #include "llvm/Transforms/SampleProfile.h"
84 #include "llvm/Transforms/Scalar/ADCE.h"
85 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h"
86 #include "llvm/Transforms/Scalar/BDCE.h"
87 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
88 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h"
89 #include "llvm/Transforms/Scalar/DCE.h"
90 #include "llvm/Transforms/Scalar/DeadStoreElimination.h"
91 #include "llvm/Transforms/Scalar/EarlyCSE.h"
92 #include "llvm/Transforms/Scalar/Float2Int.h"
93 #include "llvm/Transforms/Scalar/GVN.h"
94 #include "llvm/Transforms/Scalar/GuardWidening.h"
95 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
96 #include "llvm/Transforms/Scalar/JumpThreading.h"
97 #include "llvm/Transforms/Scalar/LICM.h"
98 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h"
99 #include "llvm/Transforms/Scalar/LoopDeletion.h"
100 #include "llvm/Transforms/Scalar/LoopDistribute.h"
101 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h"
102 #include "llvm/Transforms/Scalar/LoopInstSimplify.h"
103 #include "llvm/Transforms/Scalar/LoopRotation.h"
104 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h"
105 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
106 #include "llvm/Transforms/Scalar/LoopUnrollPass.h"
107 #include "llvm/Transforms/Scalar/LowerAtomic.h"
108 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h"
109 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h"
110 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h"
111 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h"
112 #include "llvm/Transforms/Scalar/NaryReassociate.h"
113 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
114 #include "llvm/Transforms/Scalar/Reassociate.h"
115 #include "llvm/Transforms/Scalar/SCCP.h"
116 #include "llvm/Transforms/Scalar/SROA.h"
117 #include "llvm/Transforms/Scalar/SimplifyCFG.h"
118 #include "llvm/Transforms/Scalar/Sink.h"
119 #include "llvm/Transforms/Scalar/SpeculativeExecution.h"
120 #include "llvm/Transforms/Scalar/TailRecursionElimination.h"
121 #include "llvm/Transforms/Utils/AddDiscriminators.h"
122 #include "llvm/Transforms/Utils/BreakCriticalEdges.h"
123 #include "llvm/Transforms/Utils/LCSSA.h"
124 #include "llvm/Transforms/Utils/LoopSimplify.h"
125 #include "llvm/Transforms/Utils/LowerInvoke.h"
126 #include "llvm/Transforms/Utils/Mem2Reg.h"
127 #include "llvm/Transforms/Utils/MemorySSA.h"
128 #include "llvm/Transforms/Utils/NameAnonGlobals.h"
129 #include "llvm/Transforms/Utils/SimplifyInstructions.h"
130 #include "llvm/Transforms/Utils/SymbolRewriter.h"
131 #include "llvm/Transforms/Vectorize/LoopVectorize.h"
132 #include "llvm/Transforms/Vectorize/SLPVectorizer.h"
133 
134 #include <type_traits>
135 
136 using namespace llvm;
137 
138 static Regex DefaultAliasRegex("^(default|lto-pre-link|lto)<(O[0123sz])>$");
139 
140 namespace {
141 
142 /// \brief No-op module pass which does nothing.
143 struct NoOpModulePass {
144   PreservedAnalyses run(Module &M, ModuleAnalysisManager &) {
145     return PreservedAnalyses::all();
146   }
147   static StringRef name() { return "NoOpModulePass"; }
148 };
149 
150 /// \brief No-op module analysis.
151 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> {
152   friend AnalysisInfoMixin<NoOpModuleAnalysis>;
153   static char PassID;
154 
155 public:
156   struct Result {};
157   Result run(Module &, ModuleAnalysisManager &) { return Result(); }
158   static StringRef name() { return "NoOpModuleAnalysis"; }
159 };
160 
161 /// \brief No-op CGSCC pass which does nothing.
162 struct NoOpCGSCCPass {
163   PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &,
164                         LazyCallGraph &, CGSCCUpdateResult &UR) {
165     return PreservedAnalyses::all();
166   }
167   static StringRef name() { return "NoOpCGSCCPass"; }
168 };
169 
170 /// \brief No-op CGSCC analysis.
171 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> {
172   friend AnalysisInfoMixin<NoOpCGSCCAnalysis>;
173   static char PassID;
174 
175 public:
176   struct Result {};
177   Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) {
178     return Result();
179   }
180   static StringRef name() { return "NoOpCGSCCAnalysis"; }
181 };
182 
183 /// \brief No-op function pass which does nothing.
184 struct NoOpFunctionPass {
185   PreservedAnalyses run(Function &F, FunctionAnalysisManager &) {
186     return PreservedAnalyses::all();
187   }
188   static StringRef name() { return "NoOpFunctionPass"; }
189 };
190 
191 /// \brief No-op function analysis.
192 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> {
193   friend AnalysisInfoMixin<NoOpFunctionAnalysis>;
194   static char PassID;
195 
196 public:
197   struct Result {};
198   Result run(Function &, FunctionAnalysisManager &) { return Result(); }
199   static StringRef name() { return "NoOpFunctionAnalysis"; }
200 };
201 
202 /// \brief No-op loop pass which does nothing.
203 struct NoOpLoopPass {
204   PreservedAnalyses run(Loop &L, LoopAnalysisManager &) {
205     return PreservedAnalyses::all();
206   }
207   static StringRef name() { return "NoOpLoopPass"; }
208 };
209 
210 /// \brief No-op loop analysis.
211 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> {
212   friend AnalysisInfoMixin<NoOpLoopAnalysis>;
213   static char PassID;
214 
215 public:
216   struct Result {};
217   Result run(Loop &, LoopAnalysisManager &) { return Result(); }
218   static StringRef name() { return "NoOpLoopAnalysis"; }
219 };
220 
221 char NoOpModuleAnalysis::PassID;
222 char NoOpCGSCCAnalysis::PassID;
223 char NoOpFunctionAnalysis::PassID;
224 char NoOpLoopAnalysis::PassID;
225 
226 } // End anonymous namespace.
227 
228 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) {
229 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
230   MAM.registerPass([&] { return CREATE_PASS; });
231 #include "PassRegistry.def"
232 }
233 
234 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) {
235 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
236   CGAM.registerPass([&] { return CREATE_PASS; });
237 #include "PassRegistry.def"
238 }
239 
240 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) {
241 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
242   FAM.registerPass([&] { return CREATE_PASS; });
243 #include "PassRegistry.def"
244 }
245 
246 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) {
247 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
248   LAM.registerPass([&] { return CREATE_PASS; });
249 #include "PassRegistry.def"
250 }
251 
252 void PassBuilder::addPerModuleDefaultPipeline(ModulePassManager &MPM,
253                                               OptimizationLevel Level,
254                                               bool DebugLogging) {
255   // FIXME: Finish fleshing this out to match the legacy pipelines.
256   FunctionPassManager EarlyFPM(DebugLogging);
257   EarlyFPM.addPass(SimplifyCFGPass());
258   EarlyFPM.addPass(SROA());
259   EarlyFPM.addPass(EarlyCSEPass());
260   EarlyFPM.addPass(LowerExpectIntrinsicPass());
261 
262   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM)));
263 }
264 
265 void PassBuilder::addLTOPreLinkDefaultPipeline(ModulePassManager &MPM,
266                                                OptimizationLevel Level,
267                                                bool DebugLogging) {
268   // FIXME: We should use a customized pre-link pipeline!
269   addPerModuleDefaultPipeline(MPM, Level, DebugLogging);
270 }
271 
272 void PassBuilder::addLTODefaultPipeline(ModulePassManager &MPM,
273                                         OptimizationLevel Level,
274                                         bool DebugLogging) {
275   // FIXME: Finish fleshing this out to match the legacy LTO pipelines.
276   FunctionPassManager LateFPM(DebugLogging);
277   LateFPM.addPass(InstCombinePass());
278   LateFPM.addPass(SimplifyCFGPass());
279 
280   MPM.addPass(createModuleToFunctionPassAdaptor(std::move(LateFPM)));
281 }
282 
283 static Optional<int> parseRepeatPassName(StringRef Name) {
284   if (!Name.consume_front("repeat<") || !Name.consume_back(">"))
285     return None;
286   int Count;
287   if (Name.getAsInteger(0, Count) || Count <= 0)
288     return None;
289   return Count;
290 }
291 
292 static bool isModulePassName(StringRef Name) {
293   // Manually handle aliases for pre-configured pipeline fragments.
294   if (Name.startswith("default") || Name.startswith("lto"))
295     return DefaultAliasRegex.match(Name);
296 
297   // Explicitly handle pass manager names.
298   if (Name == "module")
299     return true;
300   if (Name == "cgscc")
301     return true;
302   if (Name == "function")
303     return true;
304 
305   // Explicitly handle custom-parsed pass names.
306   if (parseRepeatPassName(Name))
307     return true;
308 
309 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
310   if (Name == NAME)                                                            \
311     return true;
312 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
313   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
314     return true;
315 #include "PassRegistry.def"
316 
317   return false;
318 }
319 
320 static bool isCGSCCPassName(StringRef Name) {
321   // Explicitly handle pass manager names.
322   if (Name == "cgscc")
323     return true;
324   if (Name == "function")
325     return true;
326 
327   // Explicitly handle custom-parsed pass names.
328   if (parseRepeatPassName(Name))
329     return true;
330 
331 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
332   if (Name == NAME)                                                            \
333     return true;
334 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
335   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
336     return true;
337 #include "PassRegistry.def"
338 
339   return false;
340 }
341 
342 static bool isFunctionPassName(StringRef Name) {
343   // Explicitly handle pass manager names.
344   if (Name == "function")
345     return true;
346   if (Name == "loop")
347     return true;
348 
349   // Explicitly handle custom-parsed pass names.
350   if (parseRepeatPassName(Name))
351     return true;
352 
353 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
354   if (Name == NAME)                                                            \
355     return true;
356 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
357   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
358     return true;
359 #include "PassRegistry.def"
360 
361   return false;
362 }
363 
364 static bool isLoopPassName(StringRef Name) {
365   // Explicitly handle pass manager names.
366   if (Name == "loop")
367     return true;
368 
369   // Explicitly handle custom-parsed pass names.
370   if (parseRepeatPassName(Name))
371     return true;
372 
373 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
374   if (Name == NAME)                                                            \
375     return true;
376 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
377   if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">")           \
378     return true;
379 #include "PassRegistry.def"
380 
381   return false;
382 }
383 
384 Optional<std::vector<PassBuilder::PipelineElement>>
385 PassBuilder::parsePipelineText(StringRef Text) {
386   std::vector<PipelineElement> ResultPipeline;
387 
388   SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = {
389       &ResultPipeline};
390   for (;;) {
391     std::vector<PipelineElement> &Pipeline = *PipelineStack.back();
392     size_t Pos = Text.find_first_of(",()");
393     Pipeline.push_back({Text.substr(0, Pos), {}});
394 
395     // If we have a single terminating name, we're done.
396     if (Pos == Text.npos)
397       break;
398 
399     char Sep = Text[Pos];
400     Text = Text.substr(Pos + 1);
401     if (Sep == ',')
402       // Just a name ending in a comma, continue.
403       continue;
404 
405     if (Sep == '(') {
406       // Push the inner pipeline onto the stack to continue processing.
407       PipelineStack.push_back(&Pipeline.back().InnerPipeline);
408       continue;
409     }
410 
411     assert(Sep == ')' && "Bogus separator!");
412     // When handling the close parenthesis, we greedily consume them to avoid
413     // empty strings in the pipeline.
414     do {
415       // If we try to pop the outer pipeline we have unbalanced parentheses.
416       if (PipelineStack.size() == 1)
417         return None;
418 
419       PipelineStack.pop_back();
420     } while (Text.consume_front(")"));
421 
422     // Check if we've finished parsing.
423     if (Text.empty())
424       break;
425 
426     // Otherwise, the end of an inner pipeline always has to be followed by
427     // a comma, and then we can continue.
428     if (!Text.consume_front(","))
429       return None;
430   }
431 
432   if (PipelineStack.size() > 1)
433     // Unbalanced paretheses.
434     return None;
435 
436   assert(PipelineStack.back() == &ResultPipeline &&
437          "Wrong pipeline at the bottom of the stack!");
438   return {std::move(ResultPipeline)};
439 }
440 
441 bool PassBuilder::parseModulePass(ModulePassManager &MPM,
442                                   const PipelineElement &E, bool VerifyEachPass,
443                                   bool DebugLogging) {
444   auto &Name = E.Name;
445   auto &InnerPipeline = E.InnerPipeline;
446 
447   // First handle complex passes like the pass managers which carry pipelines.
448   if (!InnerPipeline.empty()) {
449     if (Name == "module") {
450       ModulePassManager NestedMPM(DebugLogging);
451       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
452                                    DebugLogging))
453         return false;
454       MPM.addPass(std::move(NestedMPM));
455       return true;
456     }
457     if (Name == "cgscc") {
458       CGSCCPassManager CGPM(DebugLogging);
459       if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass,
460                                   DebugLogging))
461         return false;
462       MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM),
463                                                           DebugLogging));
464       return true;
465     }
466     if (Name == "function") {
467       FunctionPassManager FPM(DebugLogging);
468       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
469                                      DebugLogging))
470         return false;
471       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
472       return true;
473     }
474     if (auto Count = parseRepeatPassName(Name)) {
475       ModulePassManager NestedMPM(DebugLogging);
476       if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass,
477                                    DebugLogging))
478         return false;
479       MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM)));
480       return true;
481     }
482     // Normal passes can't have pipelines.
483     return false;
484   }
485 
486   // Manually handle aliases for pre-configured pipeline fragments.
487   if (Name.startswith("default") || Name.startswith("lto")) {
488     SmallVector<StringRef, 3> Matches;
489     if (!DefaultAliasRegex.match(Name, &Matches))
490       return false;
491     assert(Matches.size() == 3 && "Must capture two matched strings!");
492 
493     OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2])
494         .Case("O0", O0)
495         .Case("O1", O1)
496         .Case("O2", O2)
497         .Case("O3", O3)
498         .Case("Os", Os)
499         .Case("Oz", Oz);
500 
501     if (Matches[1] == "default") {
502       addPerModuleDefaultPipeline(MPM, L, DebugLogging);
503     } else if (Matches[1] == "lto-pre-link") {
504       addLTOPreLinkDefaultPipeline(MPM, L, DebugLogging);
505     } else {
506       assert(Matches[1] == "lto" && "Not one of the matched options!");
507       addLTODefaultPipeline(MPM, L, DebugLogging);
508     }
509     return true;
510   }
511 
512   // Finally expand the basic registered passes from the .inc file.
513 #define MODULE_PASS(NAME, CREATE_PASS)                                         \
514   if (Name == NAME) {                                                          \
515     MPM.addPass(CREATE_PASS);                                                  \
516     return true;                                                               \
517   }
518 #define MODULE_ANALYSIS(NAME, CREATE_PASS)                                     \
519   if (Name == "require<" NAME ">") {                                           \
520     MPM.addPass(                                                               \
521         RequireAnalysisPass<                                                   \
522             std::remove_reference<decltype(CREATE_PASS)>::type, Module>());    \
523     return true;                                                               \
524   }                                                                            \
525   if (Name == "invalidate<" NAME ">") {                                        \
526     MPM.addPass(InvalidateAnalysisPass<                                        \
527                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
528     return true;                                                               \
529   }
530 #include "PassRegistry.def"
531 
532   return false;
533 }
534 
535 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM,
536                                  const PipelineElement &E, bool VerifyEachPass,
537                                  bool DebugLogging) {
538   auto &Name = E.Name;
539   auto &InnerPipeline = E.InnerPipeline;
540 
541   // First handle complex passes like the pass managers which carry pipelines.
542   if (!InnerPipeline.empty()) {
543     if (Name == "cgscc") {
544       CGSCCPassManager NestedCGPM(DebugLogging);
545       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
546                                   DebugLogging))
547         return false;
548       // Add the nested pass manager with the appropriate adaptor.
549       CGPM.addPass(std::move(NestedCGPM));
550       return true;
551     }
552     if (Name == "function") {
553       FunctionPassManager FPM(DebugLogging);
554       if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass,
555                                      DebugLogging))
556         return false;
557       // Add the nested pass manager with the appropriate adaptor.
558       CGPM.addPass(
559           createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging));
560       return true;
561     }
562     if (auto Count = parseRepeatPassName(Name)) {
563       CGSCCPassManager NestedCGPM(DebugLogging);
564       if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass,
565                                   DebugLogging))
566         return false;
567       CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM)));
568       return true;
569     }
570     // Normal passes can't have pipelines.
571     return false;
572   }
573 
574   // Now expand the basic registered passes from the .inc file.
575 #define CGSCC_PASS(NAME, CREATE_PASS)                                          \
576   if (Name == NAME) {                                                          \
577     CGPM.addPass(CREATE_PASS);                                                 \
578     return true;                                                               \
579   }
580 #define CGSCC_ANALYSIS(NAME, CREATE_PASS)                                      \
581   if (Name == "require<" NAME ">") {                                           \
582     CGPM.addPass(RequireAnalysisPass<                                          \
583                  std::remove_reference<decltype(CREATE_PASS)>::type,           \
584                  LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &,    \
585                  CGSCCUpdateResult &>());                                      \
586     return true;                                                               \
587   }                                                                            \
588   if (Name == "invalidate<" NAME ">") {                                        \
589     CGPM.addPass(InvalidateAnalysisPass<                                       \
590                  std::remove_reference<decltype(CREATE_PASS)>::type>());       \
591     return true;                                                               \
592   }
593 #include "PassRegistry.def"
594 
595   return false;
596 }
597 
598 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM,
599                                     const PipelineElement &E,
600                                     bool VerifyEachPass, bool DebugLogging) {
601   auto &Name = E.Name;
602   auto &InnerPipeline = E.InnerPipeline;
603 
604   // First handle complex passes like the pass managers which carry pipelines.
605   if (!InnerPipeline.empty()) {
606     if (Name == "function") {
607       FunctionPassManager NestedFPM(DebugLogging);
608       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
609                                      DebugLogging))
610         return false;
611       // Add the nested pass manager with the appropriate adaptor.
612       FPM.addPass(std::move(NestedFPM));
613       return true;
614     }
615     if (Name == "loop") {
616       LoopPassManager LPM(DebugLogging);
617       if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass,
618                                  DebugLogging))
619         return false;
620       // Add the nested pass manager with the appropriate adaptor.
621       FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM)));
622       return true;
623     }
624     if (auto Count = parseRepeatPassName(Name)) {
625       FunctionPassManager NestedFPM(DebugLogging);
626       if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass,
627                                      DebugLogging))
628         return false;
629       FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM)));
630       return true;
631     }
632     // Normal passes can't have pipelines.
633     return false;
634   }
635 
636   // Now expand the basic registered passes from the .inc file.
637 #define FUNCTION_PASS(NAME, CREATE_PASS)                                       \
638   if (Name == NAME) {                                                          \
639     FPM.addPass(CREATE_PASS);                                                  \
640     return true;                                                               \
641   }
642 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS)                                   \
643   if (Name == "require<" NAME ">") {                                           \
644     FPM.addPass(                                                               \
645         RequireAnalysisPass<                                                   \
646             std::remove_reference<decltype(CREATE_PASS)>::type, Function>());  \
647     return true;                                                               \
648   }                                                                            \
649   if (Name == "invalidate<" NAME ">") {                                        \
650     FPM.addPass(InvalidateAnalysisPass<                                        \
651                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
652     return true;                                                               \
653   }
654 #include "PassRegistry.def"
655 
656   return false;
657 }
658 
659 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E,
660                                 bool VerifyEachPass, bool DebugLogging) {
661   StringRef Name = E.Name;
662   auto &InnerPipeline = E.InnerPipeline;
663 
664   // First handle complex passes like the pass managers which carry pipelines.
665   if (!InnerPipeline.empty()) {
666     if (Name == "loop") {
667       LoopPassManager NestedLPM(DebugLogging);
668       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
669                                  DebugLogging))
670         return false;
671       // Add the nested pass manager with the appropriate adaptor.
672       LPM.addPass(std::move(NestedLPM));
673       return true;
674     }
675     if (auto Count = parseRepeatPassName(Name)) {
676       LoopPassManager NestedLPM(DebugLogging);
677       if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass,
678                                  DebugLogging))
679         return false;
680       LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM)));
681       return true;
682     }
683     // Normal passes can't have pipelines.
684     return false;
685   }
686 
687   // Now expand the basic registered passes from the .inc file.
688 #define LOOP_PASS(NAME, CREATE_PASS)                                           \
689   if (Name == NAME) {                                                          \
690     LPM.addPass(CREATE_PASS);                                                  \
691     return true;                                                               \
692   }
693 #define LOOP_ANALYSIS(NAME, CREATE_PASS)                                       \
694   if (Name == "require<" NAME ">") {                                           \
695     LPM.addPass(RequireAnalysisPass<                                           \
696                 std::remove_reference<decltype(CREATE_PASS)>::type, Loop>());  \
697     return true;                                                               \
698   }                                                                            \
699   if (Name == "invalidate<" NAME ">") {                                        \
700     LPM.addPass(InvalidateAnalysisPass<                                        \
701                 std::remove_reference<decltype(CREATE_PASS)>::type>());        \
702     return true;                                                               \
703   }
704 #include "PassRegistry.def"
705 
706   return false;
707 }
708 
709 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) {
710 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS)                               \
711   if (Name == NAME) {                                                          \
712     AA.registerModuleAnalysis<                                                 \
713         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
714     return true;                                                               \
715   }
716 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS)                             \
717   if (Name == NAME) {                                                          \
718     AA.registerFunctionAnalysis<                                               \
719         std::remove_reference<decltype(CREATE_PASS)>::type>();                 \
720     return true;                                                               \
721   }
722 #include "PassRegistry.def"
723 
724   return false;
725 }
726 
727 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM,
728                                         ArrayRef<PipelineElement> Pipeline,
729                                         bool VerifyEachPass,
730                                         bool DebugLogging) {
731   for (const auto &Element : Pipeline) {
732     if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging))
733       return false;
734     // FIXME: No verifier support for Loop passes!
735   }
736   return true;
737 }
738 
739 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM,
740                                             ArrayRef<PipelineElement> Pipeline,
741                                             bool VerifyEachPass,
742                                             bool DebugLogging) {
743   for (const auto &Element : Pipeline) {
744     if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging))
745       return false;
746     if (VerifyEachPass)
747       FPM.addPass(VerifierPass());
748   }
749   return true;
750 }
751 
752 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM,
753                                          ArrayRef<PipelineElement> Pipeline,
754                                          bool VerifyEachPass,
755                                          bool DebugLogging) {
756   for (const auto &Element : Pipeline) {
757     if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging))
758       return false;
759     // FIXME: No verifier support for CGSCC passes!
760   }
761   return true;
762 }
763 
764 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM,
765                                        FunctionAnalysisManager &FAM,
766                                        CGSCCAnalysisManager &CGAM,
767                                        ModuleAnalysisManager &MAM) {
768   MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); });
769   MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); });
770   CGAM.registerPass([&] { return FunctionAnalysisManagerCGSCCProxy(FAM); });
771   CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); });
772   FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); });
773   FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); });
774   FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); });
775   LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); });
776 }
777 
778 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM,
779                                           ArrayRef<PipelineElement> Pipeline,
780                                           bool VerifyEachPass,
781                                           bool DebugLogging) {
782   for (const auto &Element : Pipeline) {
783     if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging))
784       return false;
785     if (VerifyEachPass)
786       MPM.addPass(VerifierPass());
787   }
788   return true;
789 }
790 
791 // Primary pass pipeline description parsing routine.
792 // FIXME: Should this routine accept a TargetMachine or require the caller to
793 // pre-populate the analysis managers with target-specific stuff?
794 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM,
795                                     StringRef PipelineText, bool VerifyEachPass,
796                                     bool DebugLogging) {
797   auto Pipeline = parsePipelineText(PipelineText);
798   if (!Pipeline || Pipeline->empty())
799     return false;
800 
801   // If the first name isn't at the module layer, wrap the pipeline up
802   // automatically.
803   StringRef FirstName = Pipeline->front().Name;
804 
805   if (!isModulePassName(FirstName)) {
806     if (isCGSCCPassName(FirstName))
807       Pipeline = {{"cgscc", std::move(*Pipeline)}};
808     else if (isFunctionPassName(FirstName))
809       Pipeline = {{"function", std::move(*Pipeline)}};
810     else if (isLoopPassName(FirstName))
811       Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}};
812     else
813       // Unknown pass name!
814       return false;
815   }
816 
817   return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging);
818 }
819 
820 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) {
821   while (!PipelineText.empty()) {
822     StringRef Name;
823     std::tie(Name, PipelineText) = PipelineText.split(',');
824     if (!parseAAPassName(AA, Name))
825       return false;
826   }
827 
828   return true;
829 }
830