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