1 //===- Construction of codegen pass pipelines ------------------*- C++ -*--===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 /// \file
9 ///
10 /// Interfaces for registering analysis passes, producing common pass manager
11 /// configurations, and parsing of pass pipelines.
12 ///
13 //===----------------------------------------------------------------------===//
14 
15 #ifndef LLVM_CODEGEN_CODEGENPASSBUILDER_H
16 #define LLVM_CODEGEN_CODEGENPASSBUILDER_H
17 
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Analysis/AliasAnalysis.h"
21 #include "llvm/Analysis/BasicAliasAnalysis.h"
22 #include "llvm/Analysis/ScopedNoAliasAA.h"
23 #include "llvm/Analysis/TargetTransformInfo.h"
24 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
25 #include "llvm/CodeGen/ExpandReductions.h"
26 #include "llvm/CodeGen/MachinePassManager.h"
27 #include "llvm/CodeGen/PreISelIntrinsicLowering.h"
28 #include "llvm/CodeGen/ReplaceWithVeclib.h"
29 #include "llvm/CodeGen/UnreachableBlockElim.h"
30 #include "llvm/IR/PassManager.h"
31 #include "llvm/IR/Verifier.h"
32 #include "llvm/IRPrinter/IRPrintingPasses.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCTargetOptions.h"
35 #include "llvm/Support/CodeGen.h"
36 #include "llvm/Support/Debug.h"
37 #include "llvm/Support/Error.h"
38 #include "llvm/Support/ErrorHandling.h"
39 #include "llvm/Target/CGPassBuilderOption.h"
40 #include "llvm/Target/TargetMachine.h"
41 #include "llvm/Transforms/Scalar/ConstantHoisting.h"
42 #include "llvm/Transforms/Scalar/LoopPassManager.h"
43 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h"
44 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h"
45 #include "llvm/Transforms/Scalar/MergeICmps.h"
46 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h"
47 #include "llvm/Transforms/Scalar/ScalarizeMaskedMemIntrin.h"
48 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h"
49 #include "llvm/Transforms/Utils/LowerInvoke.h"
50 #include <cassert>
51 #include <type_traits>
52 #include <utility>
53 
54 namespace llvm {
55 
56 // FIXME: Dummy target independent passes definitions that have not yet been
57 // ported to new pass manager. Once they do, remove these.
58 #define DUMMY_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                      \
59   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
60     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
61     PreservedAnalyses run(Function &, FunctionAnalysisManager &) {             \
62       return PreservedAnalyses::all();                                         \
63     }                                                                          \
64   };
65 #define DUMMY_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                        \
66   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
67     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
68     PreservedAnalyses run(Module &, ModuleAnalysisManager &) {                 \
69       return PreservedAnalyses::all();                                         \
70     }                                                                          \
71   };
72 #define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                \
73   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
74     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
75     Error run(Module &, MachineFunctionAnalysisManager &) {                    \
76       return Error::success();                                                 \
77     }                                                                          \
78     PreservedAnalyses run(MachineFunction &,                                   \
79                           MachineFunctionAnalysisManager &) {                  \
80       llvm_unreachable("this api is to make new PM api happy");                \
81     }                                                                          \
82     static AnalysisKey Key;                                                    \
83   };
84 #define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)              \
85   struct PASS_NAME : public PassInfoMixin<PASS_NAME> {                         \
86     template <typename... Ts> PASS_NAME(Ts &&...) {}                           \
87     PreservedAnalyses run(MachineFunction &,                                   \
88                           MachineFunctionAnalysisManager &) {                  \
89       return PreservedAnalyses::all();                                         \
90     }                                                                          \
91     static AnalysisKey Key;                                                    \
92   };
93 #include "MachinePassRegistry.def"
94 
95 /// This class provides access to building LLVM's passes.
96 ///
97 /// Its members provide the baseline state available to passes during their
98 /// construction. The \c MachinePassRegistry.def file specifies how to construct
99 /// all of the built-in passes, and those may reference these members during
100 /// construction.
101 template <typename DerivedT> class CodeGenPassBuilder {
102 public:
103   explicit CodeGenPassBuilder(LLVMTargetMachine &TM, CGPassBuilderOption Opts,
104                               PassInstrumentationCallbacks *PIC)
105       : TM(TM), Opt(Opts), PIC(PIC) {
106     // Target could set CGPassBuilderOption::MISchedPostRA to true to achieve
107     //     substitutePass(&PostRASchedulerID, &PostMachineSchedulerID)
108 
109     // Target should override TM.Options.EnableIPRA in their target-specific
110     // LLVMTM ctor. See TargetMachine::setGlobalISel for example.
111     if (Opt.EnableIPRA)
112       TM.Options.EnableIPRA = *Opt.EnableIPRA;
113 
114     if (Opt.EnableGlobalISelAbort)
115       TM.Options.GlobalISelAbort = *Opt.EnableGlobalISelAbort;
116 
117     if (!Opt.OptimizeRegAlloc)
118       Opt.OptimizeRegAlloc = getOptLevel() != CodeGenOpt::None;
119   }
120 
121   Error buildPipeline(ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
122                       raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
123                       CodeGenFileType FileType) const;
124 
125   void registerModuleAnalyses(ModuleAnalysisManager &) const;
126   void registerFunctionAnalyses(FunctionAnalysisManager &) const;
127   void registerMachineFunctionAnalyses(MachineFunctionAnalysisManager &) const;
128   std::pair<StringRef, bool> getPassNameFromLegacyName(StringRef) const;
129 
130   void registerAnalyses(MachineFunctionAnalysisManager &MFAM) const {
131     registerModuleAnalyses(*MFAM.MAM);
132     registerFunctionAnalyses(*MFAM.FAM);
133     registerMachineFunctionAnalyses(MFAM);
134   }
135 
136   PassInstrumentationCallbacks *getPassInstrumentationCallbacks() const {
137     return PIC;
138   }
139 
140 protected:
141   template <typename PassT> using has_key_t = decltype(PassT::Key);
142 
143   template <typename PassT>
144   using is_module_pass_t = decltype(std::declval<PassT &>().run(
145       std::declval<Module &>(), std::declval<ModuleAnalysisManager &>()));
146 
147   template <typename PassT>
148   using is_function_pass_t = decltype(std::declval<PassT &>().run(
149       std::declval<Function &>(), std::declval<FunctionAnalysisManager &>()));
150 
151   // Function object to maintain state while adding codegen IR passes.
152   class AddIRPass {
153   public:
154     AddIRPass(ModulePassManager &MPM, bool DebugPM, bool Check = true)
155         : MPM(MPM) {
156       if (Check)
157         AddingFunctionPasses = false;
158     }
159     ~AddIRPass() {
160       MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM)));
161     }
162 
163     // Add Function Pass
164     template <typename PassT>
165     std::enable_if_t<is_detected<is_function_pass_t, PassT>::value>
166     operator()(PassT &&Pass) {
167       if (AddingFunctionPasses && !*AddingFunctionPasses)
168         AddingFunctionPasses = true;
169       FPM.addPass(std::forward<PassT>(Pass));
170     }
171 
172     // Add Module Pass
173     template <typename PassT>
174     std::enable_if_t<is_detected<is_module_pass_t, PassT>::value &&
175                      !is_detected<is_function_pass_t, PassT>::value>
176     operator()(PassT &&Pass) {
177       assert((!AddingFunctionPasses || !*AddingFunctionPasses) &&
178              "could not add module pass after adding function pass");
179       MPM.addPass(std::forward<PassT>(Pass));
180     }
181 
182   private:
183     ModulePassManager &MPM;
184     FunctionPassManager FPM;
185     // The codegen IR pipeline are mostly function passes with the exceptions of
186     // a few loop and module passes. `AddingFunctionPasses` make sures that
187     // we could only add module passes at the beginning of the pipeline. Once
188     // we begin adding function passes, we could no longer add module passes.
189     // This special-casing introduces less adaptor passes. If we have the need
190     // of adding module passes after function passes, we could change the
191     // implementation to accommodate that.
192     std::optional<bool> AddingFunctionPasses;
193   };
194 
195   // Function object to maintain state while adding codegen machine passes.
196   class AddMachinePass {
197   public:
198     AddMachinePass(MachineFunctionPassManager &PM) : PM(PM) {}
199 
200     template <typename PassT> void operator()(PassT &&Pass) {
201       static_assert(
202           is_detected<has_key_t, PassT>::value,
203           "Machine function pass must define a static member variable `Key`.");
204       for (auto &C : BeforeCallbacks)
205         if (!C(&PassT::Key))
206           return;
207       PM.addPass(std::forward<PassT>(Pass));
208       for (auto &C : AfterCallbacks)
209         C(&PassT::Key);
210     }
211 
212     template <typename PassT> void insertPass(AnalysisKey *ID, PassT Pass) {
213       AfterCallbacks.emplace_back(
214           [this, ID, Pass = std::move(Pass)](AnalysisKey *PassID) {
215             if (PassID == ID)
216               this->PM.addPass(std::move(Pass));
217           });
218     }
219 
220     void disablePass(AnalysisKey *ID) {
221       BeforeCallbacks.emplace_back(
222           [ID](AnalysisKey *PassID) { return PassID != ID; });
223     }
224 
225     MachineFunctionPassManager releasePM() { return std::move(PM); }
226 
227   private:
228     MachineFunctionPassManager &PM;
229     SmallVector<llvm::unique_function<bool(AnalysisKey *)>, 4> BeforeCallbacks;
230     SmallVector<llvm::unique_function<void(AnalysisKey *)>, 4> AfterCallbacks;
231   };
232 
233   LLVMTargetMachine &TM;
234   CGPassBuilderOption Opt;
235   PassInstrumentationCallbacks *PIC;
236 
237   /// Target override these hooks to parse target-specific analyses.
238   void registerTargetAnalysis(ModuleAnalysisManager &) const {}
239   void registerTargetAnalysis(FunctionAnalysisManager &) const {}
240   void registerTargetAnalysis(MachineFunctionAnalysisManager &) const {}
241   std::pair<StringRef, bool> getTargetPassNameFromLegacyName(StringRef) const {
242     return {"", false};
243   }
244 
245   template <typename TMC> TMC &getTM() const { return static_cast<TMC &>(TM); }
246   CodeGenOpt::Level getOptLevel() const { return TM.getOptLevel(); }
247 
248   /// Check whether or not GlobalISel should abort on error.
249   /// When this is disabled, GlobalISel will fall back on SDISel instead of
250   /// erroring out.
251   bool isGlobalISelAbortEnabled() const {
252     return TM.Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
253   }
254 
255   /// Check whether or not a diagnostic should be emitted when GlobalISel
256   /// uses the fallback path. In other words, it will emit a diagnostic
257   /// when GlobalISel failed and isGlobalISelAbortEnabled is false.
258   bool reportDiagnosticWhenGlobalISelFallback() const {
259     return TM.Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
260   }
261 
262   /// addInstSelector - This method should install an instruction selector pass,
263   /// which converts from LLVM code to machine instructions.
264   Error addInstSelector(AddMachinePass &) const {
265     return make_error<StringError>("addInstSelector is not overridden",
266                                    inconvertibleErrorCode());
267   }
268 
269   /// Add passes that optimize instruction level parallelism for out-of-order
270   /// targets. These passes are run while the machine code is still in SSA
271   /// form, so they can use MachineTraceMetrics to control their heuristics.
272   ///
273   /// All passes added here should preserve the MachineDominatorTree,
274   /// MachineLoopInfo, and MachineTraceMetrics analyses.
275   void addILPOpts(AddMachinePass &) const {}
276 
277   /// This method may be implemented by targets that want to run passes
278   /// immediately before register allocation.
279   void addPreRegAlloc(AddMachinePass &) const {}
280 
281   /// addPreRewrite - Add passes to the optimized register allocation pipeline
282   /// after register allocation is complete, but before virtual registers are
283   /// rewritten to physical registers.
284   ///
285   /// These passes must preserve VirtRegMap and LiveIntervals, and when running
286   /// after RABasic or RAGreedy, they should take advantage of LiveRegMatrix.
287   /// When these passes run, VirtRegMap contains legal physreg assignments for
288   /// all virtual registers.
289   ///
290   /// Note if the target overloads addRegAssignAndRewriteOptimized, this may not
291   /// be honored. This is also not generally used for the the fast variant,
292   /// where the allocation and rewriting are done in one pass.
293   void addPreRewrite(AddMachinePass &) const {}
294 
295   /// Add passes to be run immediately after virtual registers are rewritten
296   /// to physical registers.
297   void addPostRewrite(AddMachinePass &) const {}
298 
299   /// This method may be implemented by targets that want to run passes after
300   /// register allocation pass pipeline but before prolog-epilog insertion.
301   void addPostRegAlloc(AddMachinePass &) const {}
302 
303   /// This method may be implemented by targets that want to run passes after
304   /// prolog-epilog insertion and before the second instruction scheduling pass.
305   void addPreSched2(AddMachinePass &) const {}
306 
307   /// This pass may be implemented by targets that want to run passes
308   /// immediately before machine code is emitted.
309   void addPreEmitPass(AddMachinePass &) const {}
310 
311   /// Targets may add passes immediately before machine code is emitted in this
312   /// callback. This is called even later than `addPreEmitPass`.
313   // FIXME: Rename `addPreEmitPass` to something more sensible given its actual
314   // position and remove the `2` suffix here as this callback is what
315   // `addPreEmitPass` *should* be but in reality isn't.
316   void addPreEmitPass2(AddMachinePass &) const {}
317 
318   /// {{@ For GlobalISel
319   ///
320 
321   /// addPreISel - This method should add any "last minute" LLVM->LLVM
322   /// passes (which are run just before instruction selector).
323   void addPreISel(AddIRPass &) const {
324     llvm_unreachable("addPreISel is not overridden");
325   }
326 
327   /// This method should install an IR translator pass, which converts from
328   /// LLVM code to machine instructions with possibly generic opcodes.
329   Error addIRTranslator(AddMachinePass &) const {
330     return make_error<StringError>("addIRTranslator is not overridden",
331                                    inconvertibleErrorCode());
332   }
333 
334   /// This method may be implemented by targets that want to run passes
335   /// immediately before legalization.
336   void addPreLegalizeMachineIR(AddMachinePass &) const {}
337 
338   /// This method should install a legalize pass, which converts the instruction
339   /// sequence into one that can be selected by the target.
340   Error addLegalizeMachineIR(AddMachinePass &) const {
341     return make_error<StringError>("addLegalizeMachineIR is not overridden",
342                                    inconvertibleErrorCode());
343   }
344 
345   /// This method may be implemented by targets that want to run passes
346   /// immediately before the register bank selection.
347   void addPreRegBankSelect(AddMachinePass &) const {}
348 
349   /// This method should install a register bank selector pass, which
350   /// assigns register banks to virtual registers without a register
351   /// class or register banks.
352   Error addRegBankSelect(AddMachinePass &) const {
353     return make_error<StringError>("addRegBankSelect is not overridden",
354                                    inconvertibleErrorCode());
355   }
356 
357   /// This method may be implemented by targets that want to run passes
358   /// immediately before the (global) instruction selection.
359   void addPreGlobalInstructionSelect(AddMachinePass &) const {}
360 
361   /// This method should install a (global) instruction selector pass, which
362   /// converts possibly generic instructions to fully target-specific
363   /// instructions, thereby constraining all generic virtual registers to
364   /// register classes.
365   Error addGlobalInstructionSelect(AddMachinePass &) const {
366     return make_error<StringError>(
367         "addGlobalInstructionSelect is not overridden",
368         inconvertibleErrorCode());
369   }
370   /// @}}
371 
372   /// High level function that adds all passes necessary to go from llvm IR
373   /// representation to the MI representation.
374   /// Adds IR based lowering and target specific optimization passes and finally
375   /// the core instruction selection passes.
376   void addISelPasses(AddIRPass &) const;
377 
378   /// Add the actual instruction selection passes. This does not include
379   /// preparation passes on IR.
380   Error addCoreISelPasses(AddMachinePass &) const;
381 
382   /// Add the complete, standard set of LLVM CodeGen passes.
383   /// Fully developed targets will not generally override this.
384   Error addMachinePasses(AddMachinePass &) const;
385 
386   /// Add passes to lower exception handling for the code generator.
387   void addPassesToHandleExceptions(AddIRPass &) const;
388 
389   /// Add common target configurable passes that perform LLVM IR to IR
390   /// transforms following machine independent optimization.
391   void addIRPasses(AddIRPass &) const;
392 
393   /// Add pass to prepare the LLVM IR for code generation. This should be done
394   /// before exception handling preparation passes.
395   void addCodeGenPrepare(AddIRPass &) const;
396 
397   /// Add common passes that perform LLVM IR to IR transforms in preparation for
398   /// instruction selection.
399   void addISelPrepare(AddIRPass &) const;
400 
401   /// Methods with trivial inline returns are convenient points in the common
402   /// codegen pass pipeline where targets may insert passes. Methods with
403   /// out-of-line standard implementations are major CodeGen stages called by
404   /// addMachinePasses. Some targets may override major stages when inserting
405   /// passes is insufficient, but maintaining overriden stages is more work.
406   ///
407 
408   /// addMachineSSAOptimization - Add standard passes that optimize machine
409   /// instructions in SSA form.
410   void addMachineSSAOptimization(AddMachinePass &) const;
411 
412   /// addFastRegAlloc - Add the minimum set of target-independent passes that
413   /// are required for fast register allocation.
414   Error addFastRegAlloc(AddMachinePass &) const;
415 
416   /// addOptimizedRegAlloc - Add passes related to register allocation.
417   /// LLVMTargetMachine provides standard regalloc passes for most targets.
418   void addOptimizedRegAlloc(AddMachinePass &) const;
419 
420   /// Add passes that optimize machine instructions after register allocation.
421   void addMachineLateOptimization(AddMachinePass &) const;
422 
423   /// addGCPasses - Add late codegen passes that analyze code for garbage
424   /// collection. This should return true if GC info should be printed after
425   /// these passes.
426   void addGCPasses(AddMachinePass &) const {}
427 
428   /// Add standard basic block placement passes.
429   void addBlockPlacement(AddMachinePass &) const;
430 
431   using CreateMCStreamer =
432       std::function<Expected<std::unique_ptr<MCStreamer>>(MCContext &)>;
433   void addAsmPrinter(AddMachinePass &, CreateMCStreamer) const {
434     llvm_unreachable("addAsmPrinter is not overridden");
435   }
436 
437   /// Utilities for targets to add passes to the pass manager.
438   ///
439 
440   /// createTargetRegisterAllocator - Create the register allocator pass for
441   /// this target at the current optimization level.
442   void addTargetRegisterAllocator(AddMachinePass &, bool Optimized) const;
443 
444   /// addMachinePasses helper to create the target-selected or overriden
445   /// regalloc pass.
446   void addRegAllocPass(AddMachinePass &, bool Optimized) const;
447 
448   /// Add core register alloator passes which do the actual register assignment
449   /// and rewriting. \returns true if any passes were added.
450   Error addRegAssignmentFast(AddMachinePass &) const;
451   Error addRegAssignmentOptimized(AddMachinePass &) const;
452 
453 private:
454   DerivedT &derived() { return static_cast<DerivedT &>(*this); }
455   const DerivedT &derived() const {
456     return static_cast<const DerivedT &>(*this);
457   }
458 };
459 
460 template <typename Derived>
461 Error CodeGenPassBuilder<Derived>::buildPipeline(
462     ModulePassManager &MPM, MachineFunctionPassManager &MFPM,
463     raw_pwrite_stream &Out, raw_pwrite_stream *DwoOut,
464     CodeGenFileType FileType) const {
465   AddIRPass addIRPass(MPM, Opt.DebugPM);
466   addISelPasses(addIRPass);
467 
468   AddMachinePass addPass(MFPM);
469   if (auto Err = addCoreISelPasses(addPass))
470     return std::move(Err);
471 
472   if (auto Err = derived().addMachinePasses(addPass))
473     return std::move(Err);
474 
475   derived().addAsmPrinter(
476       addPass, [this, &Out, DwoOut, FileType](MCContext &Ctx) {
477         return this->TM.createMCStreamer(Out, DwoOut, FileType, Ctx);
478       });
479 
480   addPass(FreeMachineFunctionPass());
481   return Error::success();
482 }
483 
484 static inline AAManager registerAAAnalyses() {
485   AAManager AA;
486 
487   // The order in which these are registered determines their priority when
488   // being queried.
489 
490   // Basic AliasAnalysis support.
491   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
492   // BasicAliasAnalysis wins if they disagree. This is intended to help
493   // support "obvious" type-punning idioms.
494   AA.registerFunctionAnalysis<TypeBasedAA>();
495   AA.registerFunctionAnalysis<ScopedNoAliasAA>();
496   AA.registerFunctionAnalysis<BasicAA>();
497 
498   return AA;
499 }
500 
501 template <typename Derived>
502 void CodeGenPassBuilder<Derived>::registerModuleAnalyses(
503     ModuleAnalysisManager &MAM) const {
504 #define MODULE_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR)                          \
505   MAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
506 #include "MachinePassRegistry.def"
507   derived().registerTargetAnalysis(MAM);
508 }
509 
510 template <typename Derived>
511 void CodeGenPassBuilder<Derived>::registerFunctionAnalyses(
512     FunctionAnalysisManager &FAM) const {
513   FAM.registerPass([this] { return registerAAAnalyses(); });
514 
515 #define FUNCTION_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR)                        \
516   FAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
517 #include "MachinePassRegistry.def"
518   derived().registerTargetAnalysis(FAM);
519 }
520 
521 template <typename Derived>
522 void CodeGenPassBuilder<Derived>::registerMachineFunctionAnalyses(
523     MachineFunctionAnalysisManager &MFAM) const {
524 #define MACHINE_FUNCTION_ANALYSIS(NAME, PASS_NAME, CONSTRUCTOR)                \
525   MFAM.registerPass([&] { return PASS_NAME CONSTRUCTOR; });
526 #include "MachinePassRegistry.def"
527   derived().registerTargetAnalysis(MFAM);
528 }
529 
530 // FIXME: For new PM, use pass name directly in commandline seems good.
531 // Translate stringfied pass name to its old commandline name. Returns the
532 // matching legacy name and a boolean value indicating if the pass is a machine
533 // pass.
534 template <typename Derived>
535 std::pair<StringRef, bool>
536 CodeGenPassBuilder<Derived>::getPassNameFromLegacyName(StringRef Name) const {
537   std::pair<StringRef, bool> Ret;
538   if (Name.empty())
539     return Ret;
540 
541 #define FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                            \
542   if (Name == NAME)                                                            \
543     Ret = {#PASS_NAME, false};
544 #define DUMMY_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                      \
545   if (Name == NAME)                                                            \
546     Ret = {#PASS_NAME, false};
547 #define MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                              \
548   if (Name == NAME)                                                            \
549     Ret = {#PASS_NAME, false};
550 #define DUMMY_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                        \
551   if (Name == NAME)                                                            \
552     Ret = {#PASS_NAME, false};
553 #define MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                      \
554   if (Name == NAME)                                                            \
555     Ret = {#PASS_NAME, true};
556 #define DUMMY_MACHINE_MODULE_PASS(NAME, PASS_NAME, CONSTRUCTOR)                \
557   if (Name == NAME)                                                            \
558     Ret = {#PASS_NAME, true};
559 #define MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)                    \
560   if (Name == NAME)                                                            \
561     Ret = {#PASS_NAME, true};
562 #define DUMMY_MACHINE_FUNCTION_PASS(NAME, PASS_NAME, CONSTRUCTOR)              \
563   if (Name == NAME)                                                            \
564     Ret = {#PASS_NAME, true};
565 #include "llvm/CodeGen/MachinePassRegistry.def"
566 
567   if (Ret.first.empty())
568     Ret = derived().getTargetPassNameFromLegacyName(Name);
569 
570   if (Ret.first.empty())
571     report_fatal_error(Twine('\"') + Twine(Name) +
572                        Twine("\" pass could not be found."));
573 
574   return Ret;
575 }
576 
577 template <typename Derived>
578 void CodeGenPassBuilder<Derived>::addISelPasses(AddIRPass &addPass) const {
579   if (TM.useEmulatedTLS())
580     addPass(LowerEmuTLSPass());
581 
582   addPass(PreISelIntrinsicLoweringPass(TM));
583 
584   derived().addIRPasses(addPass);
585   derived().addCodeGenPrepare(addPass);
586   addPassesToHandleExceptions(addPass);
587   derived().addISelPrepare(addPass);
588 }
589 
590 /// Add common target configurable passes that perform LLVM IR to IR transforms
591 /// following machine independent optimization.
592 template <typename Derived>
593 void CodeGenPassBuilder<Derived>::addIRPasses(AddIRPass &addPass) const {
594   // Before running any passes, run the verifier to determine if the input
595   // coming from the front-end and/or optimizer is valid.
596   if (!Opt.DisableVerify)
597     addPass(VerifierPass());
598 
599   // Run loop strength reduction before anything else.
600   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableLSR) {
601     addPass(createFunctionToLoopPassAdaptor(
602         LoopStrengthReducePass(), /*UseMemorySSA*/ true, Opt.DebugPM));
603     // FIXME: use -stop-after so we could remove PrintLSR
604     if (Opt.PrintLSR)
605       addPass(PrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
606   }
607 
608   if (getOptLevel() != CodeGenOpt::None) {
609     // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
610     // loads and compares. ExpandMemCmpPass then tries to expand those calls
611     // into optimally-sized loads and compares. The transforms are enabled by a
612     // target lowering hook.
613     if (!Opt.DisableMergeICmps)
614       addPass(MergeICmpsPass());
615     addPass(ExpandMemCmpPass());
616   }
617 
618   // Run GC lowering passes for builtin collectors
619   // TODO: add a pass insertion point here
620   addPass(GCLoweringPass());
621   addPass(ShadowStackGCLoweringPass());
622   addPass(LowerConstantIntrinsicsPass());
623 
624   // Make sure that no unreachable blocks are instruction selected.
625   addPass(UnreachableBlockElimPass());
626 
627   // Prepare expensive constants for SelectionDAG.
628   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableConstantHoisting)
629     addPass(ConstantHoistingPass());
630 
631   // Replace calls to LLVM intrinsics (e.g., exp, log) operating on vector
632   // operands with calls to the corresponding functions in a vector library.
633   if (getOptLevel() != CodeGenOpt::None)
634     addPass(ReplaceWithVeclib());
635 
636   if (getOptLevel() != CodeGenOpt::None && !Opt.DisablePartialLibcallInlining)
637     addPass(PartiallyInlineLibCallsPass());
638 
639   // Instrument function entry and exit, e.g. with calls to mcount().
640   addPass(EntryExitInstrumenterPass(/*PostInlining=*/true));
641 
642   // Add scalarization of target's unsupported masked memory intrinsics pass.
643   // the unsupported intrinsic will be replaced with a chain of basic blocks,
644   // that stores/loads element one-by-one if the appropriate mask bit is set.
645   addPass(ScalarizeMaskedMemIntrinPass());
646 
647   // Expand reduction intrinsics into shuffle sequences if the target wants to.
648   addPass(ExpandReductionsPass());
649 
650   // Convert conditional moves to conditional jumps when profitable.
651   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableSelectOptimize)
652     addPass(SelectOptimizePass());
653 }
654 
655 /// Turn exception handling constructs into something the code generators can
656 /// handle.
657 template <typename Derived>
658 void CodeGenPassBuilder<Derived>::addPassesToHandleExceptions(
659     AddIRPass &addPass) const {
660   const MCAsmInfo *MCAI = TM.getMCAsmInfo();
661   assert(MCAI && "No MCAsmInfo");
662   switch (MCAI->getExceptionHandlingType()) {
663   case ExceptionHandling::SjLj:
664     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
665     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
666     // catch info can get misplaced when a selector ends up more than one block
667     // removed from the parent invoke(s). This could happen when a landing
668     // pad is shared by multiple invokes and is also a target of a normal
669     // edge from elsewhere.
670     addPass(SjLjEHPreparePass());
671     [[fallthrough]];
672   case ExceptionHandling::DwarfCFI:
673   case ExceptionHandling::ARM:
674   case ExceptionHandling::AIX:
675     addPass(DwarfEHPass(getOptLevel()));
676     break;
677   case ExceptionHandling::WinEH:
678     // We support using both GCC-style and MSVC-style exceptions on Windows, so
679     // add both preparation passes. Each pass will only actually run if it
680     // recognizes the personality function.
681     addPass(WinEHPass());
682     addPass(DwarfEHPass(getOptLevel()));
683     break;
684   case ExceptionHandling::Wasm:
685     // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
686     // on catchpads and cleanuppads because it does not outline them into
687     // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
688     // should remove PHIs there.
689     addPass(WinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
690     addPass(WasmEHPass());
691     break;
692   case ExceptionHandling::None:
693     addPass(LowerInvokePass());
694 
695     // The lower invoke pass may create unreachable code. Remove it.
696     addPass(UnreachableBlockElimPass());
697     break;
698   }
699 }
700 
701 /// Add pass to prepare the LLVM IR for code generation. This should be done
702 /// before exception handling preparation passes.
703 template <typename Derived>
704 void CodeGenPassBuilder<Derived>::addCodeGenPrepare(AddIRPass &addPass) const {
705   if (getOptLevel() != CodeGenOpt::None && !Opt.DisableCGP)
706     addPass(CodeGenPreparePass());
707   // TODO: Default ctor'd RewriteSymbolPass is no-op.
708   // addPass(RewriteSymbolPass());
709 }
710 
711 /// Add common passes that perform LLVM IR to IR transforms in preparation for
712 /// instruction selection.
713 template <typename Derived>
714 void CodeGenPassBuilder<Derived>::addISelPrepare(AddIRPass &addPass) const {
715   derived().addPreISel(addPass);
716 
717   addPass(CallBrPrepare());
718   // Add both the safe stack and the stack protection passes: each of them will
719   // only protect functions that have corresponding attributes.
720   addPass(SafeStackPass());
721   addPass(StackProtectorPass());
722 
723   if (Opt.PrintISelInput)
724     addPass(PrintFunctionPass(dbgs(),
725                               "\n\n*** Final LLVM Code input to ISel ***\n"));
726 
727   // All passes which modify the LLVM IR are now complete; run the verifier
728   // to ensure that the IR is valid.
729   if (!Opt.DisableVerify)
730     addPass(VerifierPass());
731 }
732 
733 template <typename Derived>
734 Error CodeGenPassBuilder<Derived>::addCoreISelPasses(
735     AddMachinePass &addPass) const {
736   // Enable FastISel with -fast-isel, but allow that to be overridden.
737   TM.setO0WantsFastISel(Opt.EnableFastISelOption.value_or(true));
738 
739   // Determine an instruction selector.
740   enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
741   SelectorType Selector;
742 
743   if (Opt.EnableFastISelOption && *Opt.EnableFastISelOption == true)
744     Selector = SelectorType::FastISel;
745   else if ((Opt.EnableGlobalISelOption &&
746             *Opt.EnableGlobalISelOption == true) ||
747            (TM.Options.EnableGlobalISel &&
748             (!Opt.EnableGlobalISelOption ||
749              *Opt.EnableGlobalISelOption == false)))
750     Selector = SelectorType::GlobalISel;
751   else if (TM.getOptLevel() == CodeGenOpt::None && TM.getO0WantsFastISel())
752     Selector = SelectorType::FastISel;
753   else
754     Selector = SelectorType::SelectionDAG;
755 
756   // Set consistently TM.Options.EnableFastISel and EnableGlobalISel.
757   if (Selector == SelectorType::FastISel) {
758     TM.setFastISel(true);
759     TM.setGlobalISel(false);
760   } else if (Selector == SelectorType::GlobalISel) {
761     TM.setFastISel(false);
762     TM.setGlobalISel(true);
763   }
764 
765   // Add instruction selector passes.
766   if (Selector == SelectorType::GlobalISel) {
767     if (auto Err = derived().addIRTranslator(addPass))
768       return std::move(Err);
769 
770     derived().addPreLegalizeMachineIR(addPass);
771 
772     if (auto Err = derived().addLegalizeMachineIR(addPass))
773       return std::move(Err);
774 
775     // Before running the register bank selector, ask the target if it
776     // wants to run some passes.
777     derived().addPreRegBankSelect(addPass);
778 
779     if (auto Err = derived().addRegBankSelect(addPass))
780       return std::move(Err);
781 
782     derived().addPreGlobalInstructionSelect(addPass);
783 
784     if (auto Err = derived().addGlobalInstructionSelect(addPass))
785       return std::move(Err);
786 
787     // Pass to reset the MachineFunction if the ISel failed.
788     addPass(ResetMachineFunctionPass(reportDiagnosticWhenGlobalISelFallback(),
789                                      isGlobalISelAbortEnabled()));
790 
791     // Provide a fallback path when we do not want to abort on
792     // not-yet-supported input.
793     if (!isGlobalISelAbortEnabled())
794       if (auto Err = derived().addInstSelector(addPass))
795         return std::move(Err);
796 
797   } else if (auto Err = derived().addInstSelector(addPass))
798     return std::move(Err);
799 
800   // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
801   // FinalizeISel.
802   addPass(FinalizeISelPass());
803 
804   // // Print the instruction selected machine code...
805   // printAndVerify("After Instruction Selection");
806 
807   return Error::success();
808 }
809 
810 /// Add the complete set of target-independent postISel code generator passes.
811 ///
812 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
813 /// with nontrivial configuration or multiple passes are broken out below in
814 /// add%Stage routines.
815 ///
816 /// Any CodeGenPassBuilder<Derived>::addXX routine may be overriden by the
817 /// Target. The addPre/Post methods with empty header implementations allow
818 /// injecting target-specific fixups just before or after major stages.
819 /// Additionally, targets have the flexibility to change pass order within a
820 /// stage by overriding default implementation of add%Stage routines below. Each
821 /// technique has maintainability tradeoffs because alternate pass orders are
822 /// not well supported. addPre/Post works better if the target pass is easily
823 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
824 /// the target should override the stage instead.
825 template <typename Derived>
826 Error CodeGenPassBuilder<Derived>::addMachinePasses(
827     AddMachinePass &addPass) const {
828   // Add passes that optimize machine instructions in SSA form.
829   if (getOptLevel() != CodeGenOpt::None) {
830     derived().addMachineSSAOptimization(addPass);
831   } else {
832     // If the target requests it, assign local variables to stack slots relative
833     // to one another and simplify frame index references where possible.
834     addPass(LocalStackSlotPass());
835   }
836 
837   if (TM.Options.EnableIPRA)
838     addPass(RegUsageInfoPropagationPass());
839 
840   // Run pre-ra passes.
841   derived().addPreRegAlloc(addPass);
842 
843   // Run register allocation and passes that are tightly coupled with it,
844   // including phi elimination and scheduling.
845   if (*Opt.OptimizeRegAlloc) {
846     derived().addOptimizedRegAlloc(addPass);
847   } else {
848     if (auto Err = derived().addFastRegAlloc(addPass))
849       return Err;
850   }
851 
852   // Run post-ra passes.
853   derived().addPostRegAlloc(addPass);
854 
855   addPass(RemoveRedundantDebugValuesPass());
856 
857   // Insert prolog/epilog code.  Eliminate abstract frame index references...
858   if (getOptLevel() != CodeGenOpt::None) {
859     addPass(PostRAMachineSinkingPass());
860     addPass(ShrinkWrapPass());
861   }
862 
863   addPass(PrologEpilogInserterPass());
864 
865   /// Add passes that optimize machine instructions after register allocation.
866   if (getOptLevel() != CodeGenOpt::None)
867     derived().addMachineLateOptimization(addPass);
868 
869   // Expand pseudo instructions before second scheduling pass.
870   addPass(ExpandPostRAPseudosPass());
871 
872   // Run pre-sched2 passes.
873   derived().addPreSched2(addPass);
874 
875   if (Opt.EnableImplicitNullChecks)
876     addPass(ImplicitNullChecksPass());
877 
878   // Second pass scheduler.
879   // Let Target optionally insert this pass by itself at some other
880   // point.
881   if (getOptLevel() != CodeGenOpt::None &&
882       !TM.targetSchedulesPostRAScheduling()) {
883     if (Opt.MISchedPostRA)
884       addPass(PostMachineSchedulerPass());
885     else
886       addPass(PostRASchedulerPass());
887   }
888 
889   // GC
890   derived().addGCPasses(addPass);
891 
892   // Basic block placement.
893   if (getOptLevel() != CodeGenOpt::None)
894     derived().addBlockPlacement(addPass);
895 
896   // Insert before XRay Instrumentation.
897   addPass(FEntryInserterPass());
898 
899   addPass(XRayInstrumentationPass());
900   addPass(PatchableFunctionPass());
901 
902   derived().addPreEmitPass(addPass);
903 
904   if (TM.Options.EnableIPRA)
905     // Collect register usage information and produce a register mask of
906     // clobbered registers, to be used to optimize call sites.
907     addPass(RegUsageInfoCollectorPass());
908 
909   addPass(FuncletLayoutPass());
910 
911   addPass(StackMapLivenessPass());
912   addPass(LiveDebugValuesPass());
913   addPass(MachineSanitizerBinaryMetadata());
914 
915   if (TM.Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
916       Opt.EnableMachineOutliner != RunOutliner::NeverOutline) {
917     bool RunOnAllFunctions =
918         (Opt.EnableMachineOutliner == RunOutliner::AlwaysOutline);
919     bool AddOutliner = RunOnAllFunctions || TM.Options.SupportsDefaultOutlining;
920     if (AddOutliner)
921       addPass(MachineOutlinerPass(RunOnAllFunctions));
922   }
923 
924   // Add passes that directly emit MI after all other MI passes.
925   derived().addPreEmitPass2(addPass);
926 
927   return Error::success();
928 }
929 
930 /// Add passes that optimize machine instructions in SSA form.
931 template <typename Derived>
932 void CodeGenPassBuilder<Derived>::addMachineSSAOptimization(
933     AddMachinePass &addPass) const {
934   // Pre-ra tail duplication.
935   addPass(EarlyTailDuplicatePass());
936 
937   // Optimize PHIs before DCE: removing dead PHI cycles may make more
938   // instructions dead.
939   addPass(OptimizePHIsPass());
940 
941   // This pass merges large allocas. StackSlotColoring is a different pass
942   // which merges spill slots.
943   addPass(StackColoringPass());
944 
945   // If the target requests it, assign local variables to stack slots relative
946   // to one another and simplify frame index references where possible.
947   addPass(LocalStackSlotPass());
948 
949   // With optimization, dead code should already be eliminated. However
950   // there is one known exception: lowered code for arguments that are only
951   // used by tail calls, where the tail calls reuse the incoming stack
952   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
953   addPass(DeadMachineInstructionElimPass());
954 
955   // Allow targets to insert passes that improve instruction level parallelism,
956   // like if-conversion. Such passes will typically need dominator trees and
957   // loop info, just like LICM and CSE below.
958   derived().addILPOpts(addPass);
959 
960   addPass(EarlyMachineLICMPass());
961   addPass(MachineCSEPass());
962 
963   addPass(MachineSinkingPass());
964 
965   addPass(PeepholeOptimizerPass());
966   // Clean-up the dead code that may have been generated by peephole
967   // rewriting.
968   addPass(DeadMachineInstructionElimPass());
969 }
970 
971 //===---------------------------------------------------------------------===//
972 /// Register Allocation Pass Configuration
973 //===---------------------------------------------------------------------===//
974 
975 /// Instantiate the default register allocator pass for this target for either
976 /// the optimized or unoptimized allocation path. This will be added to the pass
977 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
978 /// in the optimized case.
979 ///
980 /// A target that uses the standard regalloc pass order for fast or optimized
981 /// allocation may still override this for per-target regalloc
982 /// selection. But -regalloc=... always takes precedence.
983 template <typename Derived>
984 void CodeGenPassBuilder<Derived>::addTargetRegisterAllocator(
985     AddMachinePass &addPass, bool Optimized) const {
986   if (Optimized)
987     addPass(RAGreedyPass());
988   else
989     addPass(RAFastPass());
990 }
991 
992 /// Find and instantiate the register allocation pass requested by this target
993 /// at the current optimization level.  Different register allocators are
994 /// defined as separate passes because they may require different analysis.
995 template <typename Derived>
996 void CodeGenPassBuilder<Derived>::addRegAllocPass(AddMachinePass &addPass,
997                                                   bool Optimized) const {
998   if (Opt.RegAlloc == RegAllocType::Default)
999     // With no -regalloc= override, ask the target for a regalloc pass.
1000     derived().addTargetRegisterAllocator(addPass, Optimized);
1001   else if (Opt.RegAlloc == RegAllocType::Basic)
1002     addPass(RABasicPass());
1003   else if (Opt.RegAlloc == RegAllocType::Fast)
1004     addPass(RAFastPass());
1005   else if (Opt.RegAlloc == RegAllocType::Greedy)
1006     addPass(RAGreedyPass());
1007   else if (Opt.RegAlloc == RegAllocType::PBQP)
1008     addPass(RAPBQPPass());
1009   else
1010     llvm_unreachable("unknonwn register allocator type");
1011 }
1012 
1013 template <typename Derived>
1014 Error CodeGenPassBuilder<Derived>::addRegAssignmentFast(
1015     AddMachinePass &addPass) const {
1016   if (Opt.RegAlloc != RegAllocType::Default &&
1017       Opt.RegAlloc != RegAllocType::Fast)
1018     return make_error<StringError>(
1019         "Must use fast (default) register allocator for unoptimized regalloc.",
1020         inconvertibleErrorCode());
1021 
1022   addRegAllocPass(addPass, false);
1023   return Error::success();
1024 }
1025 
1026 template <typename Derived>
1027 Error CodeGenPassBuilder<Derived>::addRegAssignmentOptimized(
1028     AddMachinePass &addPass) const {
1029   // Add the selected register allocation pass.
1030   addRegAllocPass(addPass, true);
1031 
1032   // Allow targets to change the register assignments before rewriting.
1033   derived().addPreRewrite(addPass);
1034 
1035   // Finally rewrite virtual registers.
1036   addPass(VirtRegRewriterPass());
1037   // Perform stack slot coloring and post-ra machine LICM.
1038   //
1039   // FIXME: Re-enable coloring with register when it's capable of adding
1040   // kill markers.
1041   addPass(StackSlotColoringPass());
1042 
1043   return Error::success();
1044 }
1045 
1046 /// Add the minimum set of target-independent passes that are required for
1047 /// register allocation. No coalescing or scheduling.
1048 template <typename Derived>
1049 Error CodeGenPassBuilder<Derived>::addFastRegAlloc(
1050     AddMachinePass &addPass) const {
1051   addPass(PHIEliminationPass());
1052   addPass(TwoAddressInstructionPass());
1053   return derived().addRegAssignmentFast(addPass);
1054 }
1055 
1056 /// Add standard target-independent passes that are tightly coupled with
1057 /// optimized register allocation, including coalescing, machine instruction
1058 /// scheduling, and register allocation itself.
1059 template <typename Derived>
1060 void CodeGenPassBuilder<Derived>::addOptimizedRegAlloc(
1061     AddMachinePass &addPass) const {
1062   addPass(DetectDeadLanesPass());
1063 
1064   addPass(ProcessImplicitDefsPass());
1065 
1066   // Edge splitting is smarter with machine loop info.
1067   addPass(PHIEliminationPass());
1068 
1069   // Eventually, we want to run LiveIntervals before PHI elimination.
1070   if (Opt.EarlyLiveIntervals)
1071     addPass(LiveIntervalsPass());
1072 
1073   addPass(TwoAddressInstructionPass());
1074   addPass(RegisterCoalescerPass());
1075 
1076   // The machine scheduler may accidentally create disconnected components
1077   // when moving subregister definitions around, avoid this by splitting them to
1078   // separate vregs before. Splitting can also improve reg. allocation quality.
1079   addPass(RenameIndependentSubregsPass());
1080 
1081   // PreRA instruction scheduling.
1082   addPass(MachineSchedulerPass());
1083 
1084   if (derived().addRegAssignmentOptimized(addPass)) {
1085     // Allow targets to expand pseudo instructions depending on the choice of
1086     // registers before MachineCopyPropagation.
1087     derived().addPostRewrite(addPass);
1088 
1089     // Copy propagate to forward register uses and try to eliminate COPYs that
1090     // were not coalesced.
1091     addPass(MachineCopyPropagationPass());
1092 
1093     // Run post-ra machine LICM to hoist reloads / remats.
1094     //
1095     // FIXME: can this move into MachineLateOptimization?
1096     addPass(MachineLICMPass());
1097   }
1098 }
1099 
1100 //===---------------------------------------------------------------------===//
1101 /// Post RegAlloc Pass Configuration
1102 //===---------------------------------------------------------------------===//
1103 
1104 /// Add passes that optimize machine instructions after register allocation.
1105 template <typename Derived>
1106 void CodeGenPassBuilder<Derived>::addMachineLateOptimization(
1107     AddMachinePass &addPass) const {
1108   // Branch folding must be run after regalloc and prolog/epilog insertion.
1109   addPass(BranchFolderPass());
1110 
1111   // Tail duplication.
1112   // Note that duplicating tail just increases code size and degrades
1113   // performance for targets that require Structured Control Flow.
1114   // In addition it can also make CFG irreducible. Thus we disable it.
1115   if (!TM.requiresStructuredCFG())
1116     addPass(TailDuplicatePass());
1117 
1118   // Cleanup of redundant (identical) address/immediate loads.
1119   addPass(MachineLateInstrsCleanupPass());
1120 
1121   // Copy propagation.
1122   addPass(MachineCopyPropagationPass());
1123 }
1124 
1125 /// Add standard basic block placement passes.
1126 template <typename Derived>
1127 void CodeGenPassBuilder<Derived>::addBlockPlacement(
1128     AddMachinePass &addPass) const {
1129   addPass(MachineBlockPlacementPass());
1130   // Run a separate pass to collect block placement statistics.
1131   if (Opt.EnableBlockPlacementStats)
1132     addPass(MachineBlockPlacementStatsPass());
1133 }
1134 
1135 } // namespace llvm
1136 
1137 #endif // LLVM_CODEGEN_CODEGENPASSBUILDER_H
1138