xref: /llvm-project/llvm/lib/CodeGen/TargetPassConfig.cpp (revision e6406d568c550dc27999d96d174f8fe354ab545a)
1 //===- TargetPassConfig.cpp - Target independent code generation passes ---===//
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 //
10 // This file defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
12 //
13 //===---------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/TargetPassConfig.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/BasicAliasAnalysis.h"
20 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
21 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
22 #include "llvm/Analysis/CallGraphSCCPass.h"
23 #include "llvm/Analysis/ScopedNoAliasAA.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Analysis/TypeBasedAliasAnalysis.h"
26 #include "llvm/CodeGen/MachineFunctionPass.h"
27 #include "llvm/CodeGen/MachinePassRegistry.h"
28 #include "llvm/CodeGen/Passes.h"
29 #include "llvm/CodeGen/RegAllocRegistry.h"
30 #include "llvm/IR/IRPrintingPasses.h"
31 #include "llvm/IR/LegacyPassManager.h"
32 #include "llvm/IR/Verifier.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCTargetOptions.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CodeGen.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Threading.h"
42 #include "llvm/Support/SaveAndRestore.h"
43 #include "llvm/Target/TargetMachine.h"
44 #include "llvm/Transforms/Scalar.h"
45 #include "llvm/Transforms/Utils.h"
46 #include "llvm/Transforms/Utils/SymbolRewriter.h"
47 #include <cassert>
48 #include <string>
49 
50 using namespace llvm;
51 
52 cl::opt<bool> EnableIPRA("enable-ipra", cl::init(false), cl::Hidden,
53                          cl::desc("Enable interprocedural register allocation "
54                                   "to reduce load/store at procedure calls."));
55 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden,
56     cl::desc("Disable Post Regalloc Scheduler"));
57 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
58     cl::desc("Disable branch folding"));
59 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
60     cl::desc("Disable tail duplication"));
61 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
62     cl::desc("Disable pre-register allocation tail duplication"));
63 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
64     cl::Hidden, cl::desc("Disable probability-driven block placement"));
65 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
66     cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
67 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
68     cl::desc("Disable Stack Slot Coloring"));
69 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
70     cl::desc("Disable Machine Dead Code Elimination"));
71 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
72     cl::desc("Disable Early If-conversion"));
73 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
74     cl::desc("Disable Machine LICM"));
75 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
76     cl::desc("Disable Machine Common Subexpression Elimination"));
77 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
78     "optimize-regalloc", cl::Hidden,
79     cl::desc("Enable optimized register allocation compilation path."));
80 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
81     cl::Hidden,
82     cl::desc("Disable Machine LICM"));
83 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
84     cl::desc("Disable Machine Sinking"));
85 static cl::opt<bool> DisablePostRAMachineSink("disable-postra-machine-sink",
86     cl::Hidden,
87     cl::desc("Disable PostRA Machine Sinking"));
88 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
89     cl::desc("Disable Loop Strength Reduction Pass"));
90 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
91     cl::Hidden, cl::desc("Disable ConstantHoisting"));
92 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
93     cl::desc("Disable Codegen Prepare"));
94 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
95     cl::desc("Disable Copy Propagation pass"));
96 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
97     cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
98 static cl::opt<bool> EnableImplicitNullChecks(
99     "enable-implicit-null-checks",
100     cl::desc("Fold null checks into faulting memory operations"),
101     cl::init(false), cl::Hidden);
102 static cl::opt<bool> DisableMergeICmps("disable-mergeicmps",
103     cl::desc("Disable MergeICmps Pass"),
104     cl::init(false), cl::Hidden);
105 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
106     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
107 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
108     cl::desc("Print LLVM IR input to isel pass"));
109 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
110     cl::desc("Dump garbage collector data"));
111 static cl::opt<cl::boolOrDefault>
112     VerifyMachineCode("verify-machineinstrs", cl::Hidden,
113                       cl::desc("Verify generated machine code"),
114                       cl::ZeroOrMore);
115 enum RunOutliner { AlwaysOutline, NeverOutline, TargetDefault };
116 // Enable or disable the MachineOutliner.
117 static cl::opt<RunOutliner> EnableMachineOutliner(
118     "enable-machine-outliner", cl::desc("Enable the machine outliner"),
119     cl::Hidden, cl::ValueOptional, cl::init(TargetDefault),
120     cl::values(clEnumValN(AlwaysOutline, "always",
121                           "Run on all functions guaranteed to be beneficial"),
122                clEnumValN(NeverOutline, "never", "Disable all outlining"),
123                // Sentinel value for unspecified option.
124                clEnumValN(AlwaysOutline, "", "")));
125 // Enable or disable FastISel. Both options are needed, because
126 // FastISel is enabled by default with -fast, and we wish to be
127 // able to enable or disable fast-isel independently from -O0.
128 static cl::opt<cl::boolOrDefault>
129 EnableFastISelOption("fast-isel", cl::Hidden,
130   cl::desc("Enable the \"fast\" instruction selector"));
131 
132 static cl::opt<cl::boolOrDefault> EnableGlobalISelOption(
133     "global-isel", cl::Hidden,
134     cl::desc("Enable the \"global\" instruction selector"));
135 
136 static cl::opt<std::string> PrintMachineInstrs(
137     "print-machineinstrs", cl::ValueOptional, cl::desc("Print machine instrs"),
138     cl::value_desc("pass-name"), cl::init("option-unspecified"), cl::Hidden);
139 
140 static cl::opt<GlobalISelAbortMode> EnableGlobalISelAbort(
141     "global-isel-abort", cl::Hidden,
142     cl::desc("Enable abort calls when \"global\" instruction selection "
143              "fails to lower/select an instruction"),
144     cl::values(
145         clEnumValN(GlobalISelAbortMode::Disable, "0", "Disable the abort"),
146         clEnumValN(GlobalISelAbortMode::Enable, "1", "Enable the abort"),
147         clEnumValN(GlobalISelAbortMode::DisableWithDiag, "2",
148                    "Disable the abort but emit a diagnostic on failure")));
149 
150 // Temporary option to allow experimenting with MachineScheduler as a post-RA
151 // scheduler. Targets can "properly" enable this with
152 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
153 // Targets can return true in targetSchedulesPostRAScheduling() and
154 // insert a PostRA scheduling pass wherever it wants.
155 cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
156   cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
157 
158 // Experimental option to run live interval analysis early.
159 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
160     cl::desc("Run live interval analysis earlier in the pipeline"));
161 
162 // Experimental option to use CFL-AA in codegen
163 enum class CFLAAType { None, Steensgaard, Andersen, Both };
164 static cl::opt<CFLAAType> UseCFLAA(
165     "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
166     cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
167     cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
168                clEnumValN(CFLAAType::Steensgaard, "steens",
169                           "Enable unification-based CFL-AA"),
170                clEnumValN(CFLAAType::Andersen, "anders",
171                           "Enable inclusion-based CFL-AA"),
172                clEnumValN(CFLAAType::Both, "both",
173                           "Enable both variants of CFL-AA")));
174 
175 /// Option names for limiting the codegen pipeline.
176 /// Those are used in error reporting and we didn't want
177 /// to duplicate their names all over the place.
178 const char *StartAfterOptName = "start-after";
179 const char *StartBeforeOptName = "start-before";
180 const char *StopAfterOptName = "stop-after";
181 const char *StopBeforeOptName = "stop-before";
182 
183 static cl::opt<std::string>
184     StartAfterOpt(StringRef(StartAfterOptName),
185                   cl::desc("Resume compilation after a specific pass"),
186                   cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
187 
188 static cl::opt<std::string>
189     StartBeforeOpt(StringRef(StartBeforeOptName),
190                    cl::desc("Resume compilation before a specific pass"),
191                    cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
192 
193 static cl::opt<std::string>
194     StopAfterOpt(StringRef(StopAfterOptName),
195                  cl::desc("Stop compilation after a specific pass"),
196                  cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
197 
198 static cl::opt<std::string>
199     StopBeforeOpt(StringRef(StopBeforeOptName),
200                   cl::desc("Stop compilation before a specific pass"),
201                   cl::value_desc("pass-name"), cl::init(""), cl::Hidden);
202 
203 /// Allow standard passes to be disabled by command line options. This supports
204 /// simple binary flags that either suppress the pass or do nothing.
205 /// i.e. -disable-mypass=false has no effect.
206 /// These should be converted to boolOrDefault in order to use applyOverride.
207 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
208                                        bool Override) {
209   if (Override)
210     return IdentifyingPassPtr();
211   return PassID;
212 }
213 
214 /// Allow standard passes to be disabled by the command line, regardless of who
215 /// is adding the pass.
216 ///
217 /// StandardID is the pass identified in the standard pass pipeline and provided
218 /// to addPass(). It may be a target-specific ID in the case that the target
219 /// directly adds its own pass, but in that case we harmlessly fall through.
220 ///
221 /// TargetID is the pass that the target has configured to override StandardID.
222 ///
223 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
224 /// pass to run. This allows multiple options to control a single pass depending
225 /// on where in the pipeline that pass is added.
226 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
227                                        IdentifyingPassPtr TargetID) {
228   if (StandardID == &PostRASchedulerID)
229     return applyDisable(TargetID, DisablePostRASched);
230 
231   if (StandardID == &BranchFolderPassID)
232     return applyDisable(TargetID, DisableBranchFold);
233 
234   if (StandardID == &TailDuplicateID)
235     return applyDisable(TargetID, DisableTailDuplicate);
236 
237   if (StandardID == &EarlyTailDuplicateID)
238     return applyDisable(TargetID, DisableEarlyTailDup);
239 
240   if (StandardID == &MachineBlockPlacementID)
241     return applyDisable(TargetID, DisableBlockPlacement);
242 
243   if (StandardID == &StackSlotColoringID)
244     return applyDisable(TargetID, DisableSSC);
245 
246   if (StandardID == &DeadMachineInstructionElimID)
247     return applyDisable(TargetID, DisableMachineDCE);
248 
249   if (StandardID == &EarlyIfConverterID)
250     return applyDisable(TargetID, DisableEarlyIfConversion);
251 
252   if (StandardID == &EarlyMachineLICMID)
253     return applyDisable(TargetID, DisableMachineLICM);
254 
255   if (StandardID == &MachineCSEID)
256     return applyDisable(TargetID, DisableMachineCSE);
257 
258   if (StandardID == &MachineLICMID)
259     return applyDisable(TargetID, DisablePostRAMachineLICM);
260 
261   if (StandardID == &MachineSinkingID)
262     return applyDisable(TargetID, DisableMachineSink);
263 
264   if (StandardID == &PostRAMachineSinkingID)
265     return applyDisable(TargetID, DisablePostRAMachineSink);
266 
267   if (StandardID == &MachineCopyPropagationID)
268     return applyDisable(TargetID, DisableCopyProp);
269 
270   return TargetID;
271 }
272 
273 //===---------------------------------------------------------------------===//
274 /// TargetPassConfig
275 //===---------------------------------------------------------------------===//
276 
277 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
278                 "Target Pass Configuration", false, false)
279 char TargetPassConfig::ID = 0;
280 
281 namespace {
282 
283 struct InsertedPass {
284   AnalysisID TargetPassID;
285   IdentifyingPassPtr InsertedPassID;
286   bool VerifyAfter;
287   bool PrintAfter;
288 
289   InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
290                bool VerifyAfter, bool PrintAfter)
291       : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
292         VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
293 
294   Pass *getInsertedPass() const {
295     assert(InsertedPassID.isValid() && "Illegal Pass ID!");
296     if (InsertedPassID.isInstance())
297       return InsertedPassID.getInstance();
298     Pass *NP = Pass::createPass(InsertedPassID.getID());
299     assert(NP && "Pass ID not registered");
300     return NP;
301   }
302 };
303 
304 } // end anonymous namespace
305 
306 namespace llvm {
307 
308 class PassConfigImpl {
309 public:
310   // List of passes explicitly substituted by this target. Normally this is
311   // empty, but it is a convenient way to suppress or replace specific passes
312   // that are part of a standard pass pipeline without overridding the entire
313   // pipeline. This mechanism allows target options to inherit a standard pass's
314   // user interface. For example, a target may disable a standard pass by
315   // default by substituting a pass ID of zero, and the user may still enable
316   // that standard pass with an explicit command line option.
317   DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
318 
319   /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
320   /// is inserted after each instance of the first one.
321   SmallVector<InsertedPass, 4> InsertedPasses;
322 };
323 
324 } // end namespace llvm
325 
326 // Out of line virtual method.
327 TargetPassConfig::~TargetPassConfig() {
328   delete Impl;
329 }
330 
331 static const PassInfo *getPassInfo(StringRef PassName) {
332   if (PassName.empty())
333     return nullptr;
334 
335   const PassRegistry &PR = *PassRegistry::getPassRegistry();
336   const PassInfo *PI = PR.getPassInfo(PassName);
337   if (!PI)
338     report_fatal_error(Twine('\"') + Twine(PassName) +
339                        Twine("\" pass is not registered."));
340   return PI;
341 }
342 
343 static AnalysisID getPassIDFromName(StringRef PassName) {
344   const PassInfo *PI = getPassInfo(PassName);
345   return PI ? PI->getTypeInfo() : nullptr;
346 }
347 
348 void TargetPassConfig::setStartStopPasses() {
349   StartBefore = getPassIDFromName(StartBeforeOpt);
350   StartAfter = getPassIDFromName(StartAfterOpt);
351   StopBefore = getPassIDFromName(StopBeforeOpt);
352   StopAfter = getPassIDFromName(StopAfterOpt);
353   if (StartBefore && StartAfter)
354     report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
355                        Twine(StartAfterOptName) + Twine(" specified!"));
356   if (StopBefore && StopAfter)
357     report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
358                        Twine(StopAfterOptName) + Twine(" specified!"));
359   Started = (StartAfter == nullptr) && (StartBefore == nullptr);
360 }
361 
362 // Out of line constructor provides default values for pass options and
363 // registers all common codegen passes.
364 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm)
365     : ImmutablePass(ID), PM(&pm), TM(&TM) {
366   Impl = new PassConfigImpl();
367 
368   // Register all target independent codegen passes to activate their PassIDs,
369   // including this pass itself.
370   initializeCodeGen(*PassRegistry::getPassRegistry());
371 
372   // Also register alias analysis passes required by codegen passes.
373   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
374   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
375 
376   if (StringRef(PrintMachineInstrs.getValue()).equals(""))
377     TM.Options.PrintMachineCode = true;
378 
379   if (EnableIPRA.getNumOccurrences())
380     TM.Options.EnableIPRA = EnableIPRA;
381   else {
382     // If not explicitly specified, use target default.
383     TM.Options.EnableIPRA = TM.useIPRA();
384   }
385 
386   if (TM.Options.EnableIPRA)
387     setRequiresCodeGenSCCOrder();
388 
389   if (EnableGlobalISelAbort.getNumOccurrences())
390     TM.Options.GlobalISelAbort = EnableGlobalISelAbort;
391 
392   setStartStopPasses();
393 }
394 
395 CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
396   return TM->getOptLevel();
397 }
398 
399 /// Insert InsertedPassID pass after TargetPassID.
400 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
401                                   IdentifyingPassPtr InsertedPassID,
402                                   bool VerifyAfter, bool PrintAfter) {
403   assert(((!InsertedPassID.isInstance() &&
404            TargetPassID != InsertedPassID.getID()) ||
405           (InsertedPassID.isInstance() &&
406            TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
407          "Insert a pass after itself!");
408   Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
409                                     PrintAfter);
410 }
411 
412 /// createPassConfig - Create a pass configuration object to be used by
413 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
414 ///
415 /// Targets may override this to extend TargetPassConfig.
416 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
417   return new TargetPassConfig(*this, PM);
418 }
419 
420 TargetPassConfig::TargetPassConfig()
421   : ImmutablePass(ID) {
422   report_fatal_error("Trying to construct TargetPassConfig without a target "
423                      "machine. Scheduling a CodeGen pass without a target "
424                      "triple set?");
425 }
426 
427 bool TargetPassConfig::willCompleteCodeGenPipeline() {
428   return StopBeforeOpt.empty() && StopAfterOpt.empty();
429 }
430 
431 bool TargetPassConfig::hasLimitedCodeGenPipeline() {
432   return !StartBeforeOpt.empty() || !StartAfterOpt.empty() ||
433          !willCompleteCodeGenPipeline();
434 }
435 
436 std::string
437 TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) const {
438   if (!hasLimitedCodeGenPipeline())
439     return std::string();
440   std::string Res;
441   static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
442                                               &StopAfterOpt, &StopBeforeOpt};
443   static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
444                                    StopAfterOptName, StopBeforeOptName};
445   bool IsFirst = true;
446   for (int Idx = 0; Idx < 4; ++Idx)
447     if (!PassNames[Idx]->empty()) {
448       if (!IsFirst)
449         Res += Separator;
450       IsFirst = false;
451       Res += OptNames[Idx];
452     }
453   return Res;
454 }
455 
456 // Helper to verify the analysis is really immutable.
457 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
458   assert(!Initialized && "PassConfig is immutable");
459   Opt = Val;
460 }
461 
462 void TargetPassConfig::substitutePass(AnalysisID StandardID,
463                                       IdentifyingPassPtr TargetID) {
464   Impl->TargetPasses[StandardID] = TargetID;
465 }
466 
467 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
468   DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
469     I = Impl->TargetPasses.find(ID);
470   if (I == Impl->TargetPasses.end())
471     return ID;
472   return I->second;
473 }
474 
475 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
476   IdentifyingPassPtr TargetID = getPassSubstitution(ID);
477   IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
478   return !FinalPtr.isValid() || FinalPtr.isInstance() ||
479       FinalPtr.getID() != ID;
480 }
481 
482 /// Add a pass to the PassManager if that pass is supposed to be run.  If the
483 /// Started/Stopped flags indicate either that the compilation should start at
484 /// a later pass or that it should stop after an earlier pass, then do not add
485 /// the pass.  Finally, compare the current pass against the StartAfter
486 /// and StopAfter options and change the Started/Stopped flags accordingly.
487 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
488   assert(!Initialized && "PassConfig is immutable");
489 
490   // Cache the Pass ID here in case the pass manager finds this pass is
491   // redundant with ones already scheduled / available, and deletes it.
492   // Fundamentally, once we add the pass to the manager, we no longer own it
493   // and shouldn't reference it.
494   AnalysisID PassID = P->getPassID();
495 
496   if (StartBefore == PassID)
497     Started = true;
498   if (StopBefore == PassID)
499     Stopped = true;
500   if (Started && !Stopped) {
501     std::string Banner;
502     // Construct banner message before PM->add() as that may delete the pass.
503     if (AddingMachinePasses && (printAfter || verifyAfter))
504       Banner = std::string("After ") + std::string(P->getPassName());
505     PM->add(P);
506     if (AddingMachinePasses) {
507       if (printAfter)
508         addPrintPass(Banner);
509       if (verifyAfter)
510         addVerifyPass(Banner);
511     }
512 
513     // Add the passes after the pass P if there is any.
514     for (auto IP : Impl->InsertedPasses) {
515       if (IP.TargetPassID == PassID)
516         addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
517     }
518   } else {
519     delete P;
520   }
521   if (StopAfter == PassID)
522     Stopped = true;
523   if (StartAfter == PassID)
524     Started = true;
525   if (Stopped && !Started)
526     report_fatal_error("Cannot stop compilation after pass that is not run");
527 }
528 
529 /// Add a CodeGen pass at this point in the pipeline after checking for target
530 /// and command line overrides.
531 ///
532 /// addPass cannot return a pointer to the pass instance because is internal the
533 /// PassManager and the instance we create here may already be freed.
534 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
535                                      bool printAfter) {
536   IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
537   IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
538   if (!FinalPtr.isValid())
539     return nullptr;
540 
541   Pass *P;
542   if (FinalPtr.isInstance())
543     P = FinalPtr.getInstance();
544   else {
545     P = Pass::createPass(FinalPtr.getID());
546     if (!P)
547       llvm_unreachable("Pass ID not registered");
548   }
549   AnalysisID FinalID = P->getPassID();
550   addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
551 
552   return FinalID;
553 }
554 
555 void TargetPassConfig::printAndVerify(const std::string &Banner) {
556   addPrintPass(Banner);
557   addVerifyPass(Banner);
558 }
559 
560 void TargetPassConfig::addPrintPass(const std::string &Banner) {
561   if (TM->shouldPrintMachineCode())
562     PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
563 }
564 
565 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
566   bool Verify = VerifyMachineCode == cl::BOU_TRUE;
567 #ifdef EXPENSIVE_CHECKS
568   if (VerifyMachineCode == cl::BOU_UNSET)
569     Verify = TM->isMachineVerifierClean();
570 #endif
571   if (Verify)
572     PM->add(createMachineVerifierPass(Banner));
573 }
574 
575 /// Add common target configurable passes that perform LLVM IR to IR transforms
576 /// following machine independent optimization.
577 void TargetPassConfig::addIRPasses() {
578   switch (UseCFLAA) {
579   case CFLAAType::Steensgaard:
580     addPass(createCFLSteensAAWrapperPass());
581     break;
582   case CFLAAType::Andersen:
583     addPass(createCFLAndersAAWrapperPass());
584     break;
585   case CFLAAType::Both:
586     addPass(createCFLAndersAAWrapperPass());
587     addPass(createCFLSteensAAWrapperPass());
588     break;
589   default:
590     break;
591   }
592 
593   // Basic AliasAnalysis support.
594   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
595   // BasicAliasAnalysis wins if they disagree. This is intended to help
596   // support "obvious" type-punning idioms.
597   addPass(createTypeBasedAAWrapperPass());
598   addPass(createScopedNoAliasAAWrapperPass());
599   addPass(createBasicAAWrapperPass());
600 
601   // Before running any passes, run the verifier to determine if the input
602   // coming from the front-end and/or optimizer is valid.
603   if (!DisableVerify)
604     addPass(createVerifierPass());
605 
606   // Run loop strength reduction before anything else.
607   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
608     addPass(createLoopStrengthReducePass());
609     if (PrintLSR)
610       addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
611   }
612 
613   if (getOptLevel() != CodeGenOpt::None) {
614     // The MergeICmpsPass tries to create memcmp calls by grouping sequences of
615     // loads and compares. ExpandMemCmpPass then tries to expand those calls
616     // into optimally-sized loads and compares. The transforms are enabled by a
617     // target lowering hook.
618     if (!DisableMergeICmps)
619       addPass(createMergeICmpsPass());
620     addPass(createExpandMemCmpPass());
621   }
622 
623   // Run GC lowering passes for builtin collectors
624   // TODO: add a pass insertion point here
625   addPass(createGCLoweringPass());
626   addPass(createShadowStackGCLoweringPass());
627 
628   // Make sure that no unreachable blocks are instruction selected.
629   addPass(createUnreachableBlockEliminationPass());
630 
631   // Prepare expensive constants for SelectionDAG.
632   if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
633     addPass(createConstantHoistingPass());
634 
635   if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
636     addPass(createPartiallyInlineLibCallsPass());
637 
638   // Instrument function entry and exit, e.g. with calls to mcount().
639   addPass(createPostInlineEntryExitInstrumenterPass());
640 
641   // Add scalarization of target's unsupported masked memory intrinsics pass.
642   // the unsupported intrinsic will be replaced with a chain of basic blocks,
643   // that stores/loads element one-by-one if the appropriate mask bit is set.
644   addPass(createScalarizeMaskedMemIntrinPass());
645 
646   // Expand reduction intrinsics into shuffle sequences if the target wants to.
647   addPass(createExpandReductionsPass());
648 }
649 
650 /// Turn exception handling constructs into something the code generators can
651 /// handle.
652 void TargetPassConfig::addPassesToHandleExceptions() {
653   const MCAsmInfo *MCAI = TM->getMCAsmInfo();
654   assert(MCAI && "No MCAsmInfo");
655   switch (MCAI->getExceptionHandlingType()) {
656   case ExceptionHandling::SjLj:
657     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
658     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
659     // catch info can get misplaced when a selector ends up more than one block
660     // removed from the parent invoke(s). This could happen when a landing
661     // pad is shared by multiple invokes and is also a target of a normal
662     // edge from elsewhere.
663     addPass(createSjLjEHPreparePass());
664     LLVM_FALLTHROUGH;
665   case ExceptionHandling::DwarfCFI:
666   case ExceptionHandling::ARM:
667     addPass(createDwarfEHPass());
668     break;
669   case ExceptionHandling::WinEH:
670     // We support using both GCC-style and MSVC-style exceptions on Windows, so
671     // add both preparation passes. Each pass will only actually run if it
672     // recognizes the personality function.
673     addPass(createWinEHPass());
674     addPass(createDwarfEHPass());
675     break;
676   case ExceptionHandling::Wasm:
677     // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
678     // on catchpads and cleanuppads because it does not outline them into
679     // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
680     // should remove PHIs there.
681     addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
682     addPass(createWasmEHPass());
683     break;
684   case ExceptionHandling::None:
685     addPass(createLowerInvokePass());
686 
687     // The lower invoke pass may create unreachable code. Remove it.
688     addPass(createUnreachableBlockEliminationPass());
689     break;
690   }
691 }
692 
693 /// Add pass to prepare the LLVM IR for code generation. This should be done
694 /// before exception handling preparation passes.
695 void TargetPassConfig::addCodeGenPrepare() {
696   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
697     addPass(createCodeGenPreparePass());
698   addPass(createRewriteSymbolsPass());
699 }
700 
701 /// Add common passes that perform LLVM IR to IR transforms in preparation for
702 /// instruction selection.
703 void TargetPassConfig::addISelPrepare() {
704   addPreISel();
705 
706   // Force codegen to run according to the callgraph.
707   if (requiresCodeGenSCCOrder())
708     addPass(new DummyCGSCCPass);
709 
710   // Add both the safe stack and the stack protection passes: each of them will
711   // only protect functions that have corresponding attributes.
712   addPass(createSafeStackPass());
713   addPass(createStackProtectorPass());
714 
715   if (PrintISelInput)
716     addPass(createPrintFunctionPass(
717         dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
718 
719   // All passes which modify the LLVM IR are now complete; run the verifier
720   // to ensure that the IR is valid.
721   if (!DisableVerify)
722     addPass(createVerifierPass());
723 }
724 
725 bool TargetPassConfig::addCoreISelPasses() {
726   // Enable FastISel with -fast-isel, but allow that to be overridden.
727   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
728   if (EnableFastISelOption == cl::BOU_TRUE ||
729       (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel() &&
730        !TM->Options.EnableGlobalISel)) {
731     TM->setFastISel(true);
732     TM->setGlobalISel(false);
733   }
734 
735   // Ask the target for an instruction selector.
736   // Explicitly enabling fast-isel should override implicitly enabled
737   // global-isel.
738   if (EnableGlobalISelOption == cl::BOU_TRUE ||
739       (EnableGlobalISelOption == cl::BOU_UNSET &&
740        TM->Options.EnableGlobalISel && EnableFastISelOption != cl::BOU_TRUE)) {
741     TM->setGlobalISel(true);
742     TM->setFastISel(false);
743 
744     SaveAndRestore<bool> SavedAddingMachinePasses(AddingMachinePasses, true);
745     if (addIRTranslator())
746       return true;
747 
748     addPreLegalizeMachineIR();
749 
750     if (addLegalizeMachineIR())
751       return true;
752 
753     // Before running the register bank selector, ask the target if it
754     // wants to run some passes.
755     addPreRegBankSelect();
756 
757     if (addRegBankSelect())
758       return true;
759 
760     addPreGlobalInstructionSelect();
761 
762     if (addGlobalInstructionSelect())
763       return true;
764 
765     // Pass to reset the MachineFunction if the ISel failed.
766     addPass(createResetMachineFunctionPass(
767         reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
768 
769     // Provide a fallback path when we do not want to abort on
770     // not-yet-supported input.
771     if (!isGlobalISelAbortEnabled() && addInstSelector())
772       return true;
773 
774   } else if (addInstSelector())
775     return true;
776 
777   return false;
778 }
779 
780 bool TargetPassConfig::addISelPasses() {
781   if (TM->useEmulatedTLS())
782     addPass(createLowerEmuTLSPass());
783 
784   addPass(createPreISelIntrinsicLoweringPass());
785   addPass(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
786   addIRPasses();
787   addCodeGenPrepare();
788   addPassesToHandleExceptions();
789   addISelPrepare();
790 
791   return addCoreISelPasses();
792 }
793 
794 /// -regalloc=... command line option.
795 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
796 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
797                RegisterPassParser<RegisterRegAlloc>>
798     RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
799              cl::desc("Register allocator to use"));
800 
801 /// Add the complete set of target-independent postISel code generator passes.
802 ///
803 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
804 /// with nontrivial configuration or multiple passes are broken out below in
805 /// add%Stage routines.
806 ///
807 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
808 /// addPre/Post methods with empty header implementations allow injecting
809 /// target-specific fixups just before or after major stages. Additionally,
810 /// targets have the flexibility to change pass order within a stage by
811 /// overriding default implementation of add%Stage routines below. Each
812 /// technique has maintainability tradeoffs because alternate pass orders are
813 /// not well supported. addPre/Post works better if the target pass is easily
814 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
815 /// the target should override the stage instead.
816 ///
817 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
818 /// before/after any target-independent pass. But it's currently overkill.
819 void TargetPassConfig::addMachinePasses() {
820   AddingMachinePasses = true;
821 
822   // Insert a machine instr printer pass after the specified pass.
823   StringRef PrintMachineInstrsPassName = PrintMachineInstrs.getValue();
824   if (!PrintMachineInstrsPassName.equals("") &&
825       !PrintMachineInstrsPassName.equals("option-unspecified")) {
826     if (const PassInfo *TPI = getPassInfo(PrintMachineInstrsPassName)) {
827       const PassRegistry *PR = PassRegistry::getPassRegistry();
828       const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
829       assert(IPI && "failed to get \"machineinstr-printer\" PassInfo!");
830       const char *TID = (const char *)(TPI->getTypeInfo());
831       const char *IID = (const char *)(IPI->getTypeInfo());
832       insertPass(TID, IID);
833     }
834   }
835 
836   // Print the instruction selected machine code...
837   printAndVerify("After Instruction Selection");
838 
839   // Expand pseudo-instructions emitted by ISel.
840   addPass(&ExpandISelPseudosID);
841 
842   // Add passes that optimize machine instructions in SSA form.
843   if (getOptLevel() != CodeGenOpt::None) {
844     addMachineSSAOptimization();
845   } else {
846     // If the target requests it, assign local variables to stack slots relative
847     // to one another and simplify frame index references where possible.
848     addPass(&LocalStackSlotAllocationID, false);
849   }
850 
851   if (TM->Options.EnableIPRA)
852     addPass(createRegUsageInfoPropPass());
853 
854   // Run pre-ra passes.
855   addPreRegAlloc();
856 
857   // Run register allocation and passes that are tightly coupled with it,
858   // including phi elimination and scheduling.
859   if (getOptimizeRegAlloc())
860     addOptimizedRegAlloc(createRegAllocPass(true));
861   else {
862     if (RegAlloc != &useDefaultRegisterAllocator &&
863         RegAlloc != &createFastRegisterAllocator)
864       report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
865     addFastRegAlloc(createRegAllocPass(false));
866   }
867 
868   // Run post-ra passes.
869   addPostRegAlloc();
870 
871   // Insert prolog/epilog code.  Eliminate abstract frame index references...
872   if (getOptLevel() != CodeGenOpt::None) {
873     addPass(&PostRAMachineSinkingID);
874     addPass(&ShrinkWrapID);
875   }
876 
877   // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
878   // do so if it hasn't been disabled, substituted, or overridden.
879   if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
880       addPass(createPrologEpilogInserterPass());
881 
882   /// Add passes that optimize machine instructions after register allocation.
883   if (getOptLevel() != CodeGenOpt::None)
884     addMachineLateOptimization();
885 
886   // Expand pseudo instructions before second scheduling pass.
887   addPass(&ExpandPostRAPseudosID);
888 
889   // Run pre-sched2 passes.
890   addPreSched2();
891 
892   if (EnableImplicitNullChecks)
893     addPass(&ImplicitNullChecksID);
894 
895   // Second pass scheduler.
896   // Let Target optionally insert this pass by itself at some other
897   // point.
898   if (getOptLevel() != CodeGenOpt::None &&
899       !TM->targetSchedulesPostRAScheduling()) {
900     if (MISchedPostRA)
901       addPass(&PostMachineSchedulerID);
902     else
903       addPass(&PostRASchedulerID);
904   }
905 
906   // GC
907   if (addGCPasses()) {
908     if (PrintGCInfo)
909       addPass(createGCInfoPrinter(dbgs()), false, false);
910   }
911 
912   // Basic block placement.
913   if (getOptLevel() != CodeGenOpt::None)
914     addBlockPlacement();
915 
916   addPreEmitPass();
917 
918   if (TM->Options.EnableIPRA)
919     // Collect register usage information and produce a register mask of
920     // clobbered registers, to be used to optimize call sites.
921     addPass(createRegUsageInfoCollector());
922 
923   addPass(&FuncletLayoutID, false);
924 
925   addPass(&StackMapLivenessID, false);
926   addPass(&LiveDebugValuesID, false);
927 
928   // Insert before XRay Instrumentation.
929   addPass(&FEntryInserterID, false);
930 
931   addPass(&XRayInstrumentationID, false);
932   addPass(&PatchableFunctionID, false);
933 
934   if (TM->Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
935       EnableMachineOutliner != NeverOutline) {
936     bool RunOnAllFunctions = (EnableMachineOutliner == AlwaysOutline);
937     bool AddOutliner = RunOnAllFunctions ||
938                        TM->Options.SupportsDefaultOutlining;
939     if (AddOutliner)
940       addPass(createMachineOutlinerPass(RunOnAllFunctions));
941   }
942 
943   // Add passes that directly emit MI after all other MI passes.
944   addPreEmitPass2();
945 
946   AddingMachinePasses = false;
947 }
948 
949 /// Add passes that optimize machine instructions in SSA form.
950 void TargetPassConfig::addMachineSSAOptimization() {
951   // Pre-ra tail duplication.
952   addPass(&EarlyTailDuplicateID);
953 
954   // Optimize PHIs before DCE: removing dead PHI cycles may make more
955   // instructions dead.
956   addPass(&OptimizePHIsID, false);
957 
958   // This pass merges large allocas. StackSlotColoring is a different pass
959   // which merges spill slots.
960   addPass(&StackColoringID, false);
961 
962   // If the target requests it, assign local variables to stack slots relative
963   // to one another and simplify frame index references where possible.
964   addPass(&LocalStackSlotAllocationID, false);
965 
966   // With optimization, dead code should already be eliminated. However
967   // there is one known exception: lowered code for arguments that are only
968   // used by tail calls, where the tail calls reuse the incoming stack
969   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
970   addPass(&DeadMachineInstructionElimID);
971 
972   // Allow targets to insert passes that improve instruction level parallelism,
973   // like if-conversion. Such passes will typically need dominator trees and
974   // loop info, just like LICM and CSE below.
975   addILPOpts();
976 
977   addPass(&EarlyMachineLICMID, false);
978   addPass(&MachineCSEID, false);
979 
980   addPass(&MachineSinkingID);
981 
982   addPass(&PeepholeOptimizerID);
983   // Clean-up the dead code that may have been generated by peephole
984   // rewriting.
985   addPass(&DeadMachineInstructionElimID);
986 }
987 
988 //===---------------------------------------------------------------------===//
989 /// Register Allocation Pass Configuration
990 //===---------------------------------------------------------------------===//
991 
992 bool TargetPassConfig::getOptimizeRegAlloc() const {
993   switch (OptimizeRegAlloc) {
994   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
995   case cl::BOU_TRUE:  return true;
996   case cl::BOU_FALSE: return false;
997   }
998   llvm_unreachable("Invalid optimize-regalloc state");
999 }
1000 
1001 /// RegisterRegAlloc's global Registry tracks allocator registration.
1002 MachinePassRegistry<RegisterRegAlloc::FunctionPassCtor>
1003     RegisterRegAlloc::Registry;
1004 
1005 /// A dummy default pass factory indicates whether the register allocator is
1006 /// overridden on the command line.
1007 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
1008 
1009 static RegisterRegAlloc
1010 defaultRegAlloc("default",
1011                 "pick register allocator based on -O option",
1012                 useDefaultRegisterAllocator);
1013 
1014 static void initializeDefaultRegisterAllocatorOnce() {
1015   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
1016 
1017   if (!Ctor) {
1018     Ctor = RegAlloc;
1019     RegisterRegAlloc::setDefault(RegAlloc);
1020   }
1021 }
1022 
1023 /// Instantiate the default register allocator pass for this target for either
1024 /// the optimized or unoptimized allocation path. This will be added to the pass
1025 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1026 /// in the optimized case.
1027 ///
1028 /// A target that uses the standard regalloc pass order for fast or optimized
1029 /// allocation may still override this for per-target regalloc
1030 /// selection. But -regalloc=... always takes precedence.
1031 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
1032   if (Optimized)
1033     return createGreedyRegisterAllocator();
1034   else
1035     return createFastRegisterAllocator();
1036 }
1037 
1038 /// Find and instantiate the register allocation pass requested by this target
1039 /// at the current optimization level.  Different register allocators are
1040 /// defined as separate passes because they may require different analysis.
1041 ///
1042 /// This helper ensures that the regalloc= option is always available,
1043 /// even for targets that override the default allocator.
1044 ///
1045 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
1046 /// this can be folded into addPass.
1047 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
1048   // Initialize the global default.
1049   llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
1050                   initializeDefaultRegisterAllocatorOnce);
1051 
1052   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
1053   if (Ctor != useDefaultRegisterAllocator)
1054     return Ctor();
1055 
1056   // With no -regalloc= override, ask the target for a regalloc pass.
1057   return createTargetRegisterAllocator(Optimized);
1058 }
1059 
1060 /// Return true if the default global register allocator is in use and
1061 /// has not be overriden on the command line with '-regalloc=...'
1062 bool TargetPassConfig::usingDefaultRegAlloc() const {
1063   return RegAlloc.getNumOccurrences() == 0;
1064 }
1065 
1066 /// Add the minimum set of target-independent passes that are required for
1067 /// register allocation. No coalescing or scheduling.
1068 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
1069   addPass(&PHIEliminationID, false);
1070   addPass(&TwoAddressInstructionPassID, false);
1071 
1072   if (RegAllocPass)
1073     addPass(RegAllocPass);
1074 }
1075 
1076 /// Add standard target-independent passes that are tightly coupled with
1077 /// optimized register allocation, including coalescing, machine instruction
1078 /// scheduling, and register allocation itself.
1079 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
1080   addPass(&DetectDeadLanesID, false);
1081 
1082   addPass(&ProcessImplicitDefsID, false);
1083 
1084   // LiveVariables currently requires pure SSA form.
1085   //
1086   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1087   // LiveVariables can be removed completely, and LiveIntervals can be directly
1088   // computed. (We still either need to regenerate kill flags after regalloc, or
1089   // preferably fix the scavenger to not depend on them).
1090   addPass(&LiveVariablesID, false);
1091 
1092   // Edge splitting is smarter with machine loop info.
1093   addPass(&MachineLoopInfoID, false);
1094   addPass(&PHIEliminationID, false);
1095 
1096   // Eventually, we want to run LiveIntervals before PHI elimination.
1097   if (EarlyLiveIntervals)
1098     addPass(&LiveIntervalsID, false);
1099 
1100   addPass(&TwoAddressInstructionPassID, false);
1101   addPass(&RegisterCoalescerID);
1102 
1103   // The machine scheduler may accidentally create disconnected components
1104   // when moving subregister definitions around, avoid this by splitting them to
1105   // separate vregs before. Splitting can also improve reg. allocation quality.
1106   addPass(&RenameIndependentSubregsID);
1107 
1108   // PreRA instruction scheduling.
1109   addPass(&MachineSchedulerID);
1110 
1111   if (RegAllocPass) {
1112     // Add the selected register allocation pass.
1113     addPass(RegAllocPass);
1114 
1115     // Allow targets to change the register assignments before rewriting.
1116     addPreRewrite();
1117 
1118     // Finally rewrite virtual registers.
1119     addPass(&VirtRegRewriterID);
1120 
1121     // Perform stack slot coloring and post-ra machine LICM.
1122     //
1123     // FIXME: Re-enable coloring with register when it's capable of adding
1124     // kill markers.
1125     addPass(&StackSlotColoringID);
1126 
1127     // Copy propagate to forward register uses and try to eliminate COPYs that
1128     // were not coalesced.
1129     addPass(&MachineCopyPropagationID);
1130 
1131     // Run post-ra machine LICM to hoist reloads / remats.
1132     //
1133     // FIXME: can this move into MachineLateOptimization?
1134     addPass(&MachineLICMID);
1135   }
1136 }
1137 
1138 //===---------------------------------------------------------------------===//
1139 /// Post RegAlloc Pass Configuration
1140 //===---------------------------------------------------------------------===//
1141 
1142 /// Add passes that optimize machine instructions after register allocation.
1143 void TargetPassConfig::addMachineLateOptimization() {
1144   // Branch folding must be run after regalloc and prolog/epilog insertion.
1145   addPass(&BranchFolderPassID);
1146 
1147   // Tail duplication.
1148   // Note that duplicating tail just increases code size and degrades
1149   // performance for targets that require Structured Control Flow.
1150   // In addition it can also make CFG irreducible. Thus we disable it.
1151   if (!TM->requiresStructuredCFG())
1152     addPass(&TailDuplicateID);
1153 
1154   // Copy propagation.
1155   addPass(&MachineCopyPropagationID);
1156 }
1157 
1158 /// Add standard GC passes.
1159 bool TargetPassConfig::addGCPasses() {
1160   addPass(&GCMachineCodeAnalysisID, false);
1161   return true;
1162 }
1163 
1164 /// Add standard basic block placement passes.
1165 void TargetPassConfig::addBlockPlacement() {
1166   if (addPass(&MachineBlockPlacementID)) {
1167     // Run a separate pass to collect block placement statistics.
1168     if (EnableBlockPlacementStats)
1169       addPass(&MachineBlockPlacementStatsID);
1170   }
1171 }
1172 
1173 //===---------------------------------------------------------------------===//
1174 /// GlobalISel Configuration
1175 //===---------------------------------------------------------------------===//
1176 bool TargetPassConfig::isGlobalISelAbortEnabled() const {
1177   return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
1178 }
1179 
1180 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
1181   return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
1182 }
1183