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