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