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