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