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