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