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(false), cl::Hidden,
179     cl::desc("Disable MIRProfileLoader before RegAlloc"));
180 // Disable MIRProfileLoader before BloackPlacement. This is for for debugging
181 // and tuning purpose.
182 static cl::opt<bool> DisableLayoutFSProfileLoader(
183     "disable-layout-fsprofile-loader", cl::init(false), cl::Hidden,
184     cl::desc("Disable MIRProfileLoader before BlockPlacement"));
185 // Specify FSProfile file name.
186 static cl::opt<std::string>
187     FSProfileFile("fs-profile-file", cl::init(""), cl::value_desc("filename"),
188                   cl::desc("Flow Sensitive profile file name."), cl::Hidden);
189 // Specify Remapping file for FSProfile.
190 static cl::opt<std::string> FSRemappingFile(
191     "fs-remapping-file", cl::init(""), cl::value_desc("filename"),
192     cl::desc("Flow Sensitive profile remapping file name."), cl::Hidden);
193 
194 // Temporary option to allow experimenting with MachineScheduler as a post-RA
195 // scheduler. Targets can "properly" enable this with
196 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
197 // Targets can return true in targetSchedulesPostRAScheduling() and
198 // insert a PostRA scheduling pass wherever it wants.
199 static cl::opt<bool> MISchedPostRA(
200     "misched-postra", cl::Hidden,
201     cl::desc(
202         "Run MachineScheduler post regalloc (independent of preRA sched)"));
203 
204 // Experimental option to run live interval analysis early.
205 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
206     cl::desc("Run live interval analysis earlier in the pipeline"));
207 
208 // 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   // For MachO, lower @llvm.global_dtors into @llvm_global_ctors with
899   // __cxa_atexit() calls to avoid emitting the deprecated __mod_term_func.
900   if (TM->getTargetTriple().isOSBinFormatMachO() &&
901       TM->Options.LowerGlobalDtorsViaCxaAtExit)
902     addPass(createLowerGlobalDtorsLegacyPass());
903 
904   // Make sure that no unreachable blocks are instruction selected.
905   addPass(createUnreachableBlockEliminationPass());
906 
907   // Prepare expensive constants for SelectionDAG.
908   if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
909     addPass(createConstantHoistingPass());
910 
911   if (getOptLevel() != CodeGenOpt::None)
912     addPass(createReplaceWithVeclibLegacyPass());
913 
914   if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
915     addPass(createPartiallyInlineLibCallsPass());
916 
917   // Expand vector predication intrinsics into standard IR instructions.
918   // This pass has to run before ScalarizeMaskedMemIntrin and ExpandReduction
919   // passes since it emits those kinds of intrinsics.
920   addPass(createExpandVectorPredicationPass());
921 
922   // Add scalarization of target's unsupported masked memory intrinsics pass.
923   // the unsupported intrinsic will be replaced with a chain of basic blocks,
924   // that stores/loads element one-by-one if the appropriate mask bit is set.
925   addPass(createScalarizeMaskedMemIntrinLegacyPass());
926 
927   // Expand reduction intrinsics into shuffle sequences if the target wants to.
928   // Allow disabling it for testing purposes.
929   if (!DisableExpandReductions)
930     addPass(createExpandReductionsPass());
931 
932   if (getOptLevel() != CodeGenOpt::None)
933     addPass(createTLSVariableHoistPass());
934 }
935 
936 /// Turn exception handling constructs into something the code generators can
937 /// handle.
938 void TargetPassConfig::addPassesToHandleExceptions() {
939   const MCAsmInfo *MCAI = TM->getMCAsmInfo();
940   assert(MCAI && "No MCAsmInfo");
941   switch (MCAI->getExceptionHandlingType()) {
942   case ExceptionHandling::SjLj:
943     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
944     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
945     // catch info can get misplaced when a selector ends up more than one block
946     // removed from the parent invoke(s). This could happen when a landing
947     // pad is shared by multiple invokes and is also a target of a normal
948     // edge from elsewhere.
949     addPass(createSjLjEHPreparePass(TM));
950     LLVM_FALLTHROUGH;
951   case ExceptionHandling::DwarfCFI:
952   case ExceptionHandling::ARM:
953   case ExceptionHandling::AIX:
954     addPass(createDwarfEHPass(getOptLevel()));
955     break;
956   case ExceptionHandling::WinEH:
957     // We support using both GCC-style and MSVC-style exceptions on Windows, so
958     // add both preparation passes. Each pass will only actually run if it
959     // recognizes the personality function.
960     addPass(createWinEHPass());
961     addPass(createDwarfEHPass(getOptLevel()));
962     break;
963   case ExceptionHandling::Wasm:
964     // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs
965     // on catchpads and cleanuppads because it does not outline them into
966     // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we
967     // should remove PHIs there.
968     addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false));
969     addPass(createWasmEHPass());
970     break;
971   case ExceptionHandling::None:
972     addPass(createLowerInvokePass());
973 
974     // The lower invoke pass may create unreachable code. Remove it.
975     addPass(createUnreachableBlockEliminationPass());
976     break;
977   }
978 }
979 
980 /// Add pass to prepare the LLVM IR for code generation. This should be done
981 /// before exception handling preparation passes.
982 void TargetPassConfig::addCodeGenPrepare() {
983   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
984     addPass(createCodeGenPreparePass());
985 }
986 
987 /// Add common passes that perform LLVM IR to IR transforms in preparation for
988 /// instruction selection.
989 void TargetPassConfig::addISelPrepare() {
990   addPreISel();
991 
992   // Force codegen to run according to the callgraph.
993   if (requiresCodeGenSCCOrder())
994     addPass(new DummyCGSCCPass);
995 
996   // Add both the safe stack and the stack protection passes: each of them will
997   // only protect functions that have corresponding attributes.
998   addPass(createSafeStackPass());
999   addPass(createStackProtectorPass());
1000 
1001   if (PrintISelInput)
1002     addPass(createPrintFunctionPass(
1003         dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
1004 
1005   // All passes which modify the LLVM IR are now complete; run the verifier
1006   // to ensure that the IR is valid.
1007   if (!DisableVerify)
1008     addPass(createVerifierPass());
1009 }
1010 
1011 bool TargetPassConfig::addCoreISelPasses() {
1012   // Enable FastISel with -fast-isel, but allow that to be overridden.
1013   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
1014 
1015   // Determine an instruction selector.
1016   enum class SelectorType { SelectionDAG, FastISel, GlobalISel };
1017   SelectorType Selector;
1018 
1019   if (EnableFastISelOption == cl::BOU_TRUE)
1020     Selector = SelectorType::FastISel;
1021   else if (EnableGlobalISelOption == cl::BOU_TRUE ||
1022            (TM->Options.EnableGlobalISel &&
1023             EnableGlobalISelOption != cl::BOU_FALSE))
1024     Selector = SelectorType::GlobalISel;
1025   else if (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel())
1026     Selector = SelectorType::FastISel;
1027   else
1028     Selector = SelectorType::SelectionDAG;
1029 
1030   // Set consistently TM->Options.EnableFastISel and EnableGlobalISel.
1031   if (Selector == SelectorType::FastISel) {
1032     TM->setFastISel(true);
1033     TM->setGlobalISel(false);
1034   } else if (Selector == SelectorType::GlobalISel) {
1035     TM->setFastISel(false);
1036     TM->setGlobalISel(true);
1037   }
1038 
1039   // FIXME: Injecting into the DAGISel pipeline seems to cause issues with
1040   //        analyses needing to be re-run. This can result in being unable to
1041   //        schedule passes (particularly with 'Function Alias Analysis
1042   //        Results'). It's not entirely clear why but AFAICT this seems to be
1043   //        due to one FunctionPassManager not being able to use analyses from a
1044   //        previous one. As we're injecting a ModulePass we break the usual
1045   //        pass manager into two. GlobalISel with the fallback path disabled
1046   //        and -run-pass seem to be unaffected. The majority of GlobalISel
1047   //        testing uses -run-pass so this probably isn't too bad.
1048   SaveAndRestore<bool> SavedDebugifyIsSafe(DebugifyIsSafe);
1049   if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled())
1050     DebugifyIsSafe = false;
1051 
1052   // Add instruction selector passes.
1053   if (Selector == SelectorType::GlobalISel) {
1054     SaveAndRestore<bool> SavedAddingMachinePasses(AddingMachinePasses, true);
1055     if (addIRTranslator())
1056       return true;
1057 
1058     addPreLegalizeMachineIR();
1059 
1060     if (addLegalizeMachineIR())
1061       return true;
1062 
1063     // Before running the register bank selector, ask the target if it
1064     // wants to run some passes.
1065     addPreRegBankSelect();
1066 
1067     if (addRegBankSelect())
1068       return true;
1069 
1070     addPreGlobalInstructionSelect();
1071 
1072     if (addGlobalInstructionSelect())
1073       return true;
1074 
1075     // Pass to reset the MachineFunction if the ISel failed.
1076     addPass(createResetMachineFunctionPass(
1077         reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
1078 
1079     // Provide a fallback path when we do not want to abort on
1080     // not-yet-supported input.
1081     if (!isGlobalISelAbortEnabled() && addInstSelector())
1082       return true;
1083 
1084   } else if (addInstSelector())
1085     return true;
1086 
1087   // Expand pseudo-instructions emitted by ISel. Don't run the verifier before
1088   // FinalizeISel.
1089   addPass(&FinalizeISelID);
1090 
1091   // Print the instruction selected machine code...
1092   printAndVerify("After Instruction Selection");
1093 
1094   return false;
1095 }
1096 
1097 bool TargetPassConfig::addISelPasses() {
1098   if (TM->useEmulatedTLS())
1099     addPass(createLowerEmuTLSPass());
1100 
1101   addPass(createPreISelIntrinsicLoweringPass());
1102   PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
1103   addIRPasses();
1104   addCodeGenPrepare();
1105   addPassesToHandleExceptions();
1106   addISelPrepare();
1107 
1108   return addCoreISelPasses();
1109 }
1110 
1111 /// -regalloc=... command line option.
1112 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
1113 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
1114                RegisterPassParser<RegisterRegAlloc>>
1115     RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator),
1116              cl::desc("Register allocator to use"));
1117 
1118 /// Add the complete set of target-independent postISel code generator passes.
1119 ///
1120 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
1121 /// with nontrivial configuration or multiple passes are broken out below in
1122 /// add%Stage routines.
1123 ///
1124 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
1125 /// addPre/Post methods with empty header implementations allow injecting
1126 /// target-specific fixups just before or after major stages. Additionally,
1127 /// targets have the flexibility to change pass order within a stage by
1128 /// overriding default implementation of add%Stage routines below. Each
1129 /// technique has maintainability tradeoffs because alternate pass orders are
1130 /// not well supported. addPre/Post works better if the target pass is easily
1131 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
1132 /// the target should override the stage instead.
1133 ///
1134 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
1135 /// before/after any target-independent pass. But it's currently overkill.
1136 void TargetPassConfig::addMachinePasses() {
1137   AddingMachinePasses = true;
1138 
1139   // Add passes that optimize machine instructions in SSA form.
1140   if (getOptLevel() != CodeGenOpt::None) {
1141     addMachineSSAOptimization();
1142   } else {
1143     // If the target requests it, assign local variables to stack slots relative
1144     // to one another and simplify frame index references where possible.
1145     addPass(&LocalStackSlotAllocationID);
1146   }
1147 
1148   if (TM->Options.EnableIPRA)
1149     addPass(createRegUsageInfoPropPass());
1150 
1151   // Run pre-ra passes.
1152   addPreRegAlloc();
1153 
1154   // Debugifying the register allocator passes seems to provoke some
1155   // non-determinism that affects CodeGen and there doesn't seem to be a point
1156   // where it becomes safe again so stop debugifying here.
1157   DebugifyIsSafe = false;
1158 
1159   // Add a FSDiscriminator pass right before RA, so that we could get
1160   // more precise SampleFDO profile for RA.
1161   if (EnableFSDiscriminator) {
1162     addPass(createMIRAddFSDiscriminatorsPass(
1163         sampleprof::FSDiscriminatorPass::Pass1));
1164     const std::string ProfileFile = getFSProfileFile(TM);
1165     if (!ProfileFile.empty() && !DisableRAFSProfileLoader)
1166       addPass(
1167           createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
1168                                      sampleprof::FSDiscriminatorPass::Pass1));
1169   }
1170 
1171   // Run register allocation and passes that are tightly coupled with it,
1172   // including phi elimination and scheduling.
1173   if (getOptimizeRegAlloc())
1174     addOptimizedRegAlloc();
1175   else
1176     addFastRegAlloc();
1177 
1178   // Run post-ra passes.
1179   addPostRegAlloc();
1180 
1181   addPass(&RemoveRedundantDebugValuesID);
1182 
1183   addPass(&FixupStatepointCallerSavedID);
1184 
1185   // Insert prolog/epilog code.  Eliminate abstract frame index references...
1186   if (getOptLevel() != CodeGenOpt::None) {
1187     addPass(&PostRAMachineSinkingID);
1188     addPass(&ShrinkWrapID);
1189   }
1190 
1191   // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
1192   // do so if it hasn't been disabled, substituted, or overridden.
1193   if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
1194       addPass(createPrologEpilogInserterPass());
1195 
1196   /// Add passes that optimize machine instructions after register allocation.
1197   if (getOptLevel() != CodeGenOpt::None)
1198     addMachineLateOptimization();
1199 
1200   // Expand pseudo instructions before second scheduling pass.
1201   addPass(&ExpandPostRAPseudosID);
1202 
1203   // Run pre-sched2 passes.
1204   addPreSched2();
1205 
1206   if (EnableImplicitNullChecks)
1207     addPass(&ImplicitNullChecksID);
1208 
1209   // Second pass scheduler.
1210   // Let Target optionally insert this pass by itself at some other
1211   // point.
1212   if (getOptLevel() != CodeGenOpt::None &&
1213       !TM->targetSchedulesPostRAScheduling()) {
1214     if (MISchedPostRA)
1215       addPass(&PostMachineSchedulerID);
1216     else
1217       addPass(&PostRASchedulerID);
1218   }
1219 
1220   // GC
1221   if (addGCPasses()) {
1222     if (PrintGCInfo)
1223       addPass(createGCInfoPrinter(dbgs()));
1224   }
1225 
1226   // Basic block placement.
1227   if (getOptLevel() != CodeGenOpt::None)
1228     addBlockPlacement();
1229 
1230   // Insert before XRay Instrumentation.
1231   addPass(&FEntryInserterID);
1232 
1233   addPass(&XRayInstrumentationID);
1234   addPass(&PatchableFunctionID);
1235 
1236   if (EnableFSDiscriminator && !FSNoFinalDiscrim)
1237     // Add FS discriminators here so that all the instruction duplicates
1238     // in different BBs get their own discriminators. With this, we can "sum"
1239     // the SampleFDO counters instead of using MAX. This will improve the
1240     // SampleFDO profile quality.
1241     addPass(createMIRAddFSDiscriminatorsPass(
1242         sampleprof::FSDiscriminatorPass::PassLast));
1243 
1244   addPreEmitPass();
1245 
1246   if (TM->Options.EnableIPRA)
1247     // Collect register usage information and produce a register mask of
1248     // clobbered registers, to be used to optimize call sites.
1249     addPass(createRegUsageInfoCollector());
1250 
1251   // FIXME: Some backends are incompatible with running the verifier after
1252   // addPreEmitPass.  Maybe only pass "false" here for those targets?
1253   addPass(&FuncletLayoutID);
1254 
1255   addPass(&StackMapLivenessID);
1256   addPass(&LiveDebugValuesID);
1257 
1258   if (TM->Options.EnableMachineOutliner && getOptLevel() != CodeGenOpt::None &&
1259       EnableMachineOutliner != RunOutliner::NeverOutline) {
1260     bool RunOnAllFunctions =
1261         (EnableMachineOutliner == RunOutliner::AlwaysOutline);
1262     bool AddOutliner =
1263         RunOnAllFunctions || TM->Options.SupportsDefaultOutlining;
1264     if (AddOutliner)
1265       addPass(createMachineOutlinerPass(RunOnAllFunctions));
1266   }
1267 
1268   // Machine function splitter uses the basic block sections feature. Both
1269   // cannot be enabled at the same time. Basic block sections takes precedence.
1270   // FIXME: In principle, BasicBlockSection::Labels and splitting can used
1271   // together. Update this check once we have addressed any issues.
1272   if (TM->getBBSectionsType() != llvm::BasicBlockSection::None) {
1273     addPass(llvm::createBasicBlockSectionsPass(TM->getBBSectionsFuncListBuf()));
1274   } else if (TM->Options.EnableMachineFunctionSplitter ||
1275              EnableMachineFunctionSplitter) {
1276     addPass(createMachineFunctionSplitterPass());
1277   }
1278 
1279   // Add passes that directly emit MI after all other MI passes.
1280   addPreEmitPass2();
1281 
1282   AddingMachinePasses = false;
1283 }
1284 
1285 /// Add passes that optimize machine instructions in SSA form.
1286 void TargetPassConfig::addMachineSSAOptimization() {
1287   // Pre-ra tail duplication.
1288   addPass(&EarlyTailDuplicateID);
1289 
1290   // Optimize PHIs before DCE: removing dead PHI cycles may make more
1291   // instructions dead.
1292   addPass(&OptimizePHIsID);
1293 
1294   // This pass merges large allocas. StackSlotColoring is a different pass
1295   // which merges spill slots.
1296   addPass(&StackColoringID);
1297 
1298   // If the target requests it, assign local variables to stack slots relative
1299   // to one another and simplify frame index references where possible.
1300   addPass(&LocalStackSlotAllocationID);
1301 
1302   // With optimization, dead code should already be eliminated. However
1303   // there is one known exception: lowered code for arguments that are only
1304   // used by tail calls, where the tail calls reuse the incoming stack
1305   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
1306   addPass(&DeadMachineInstructionElimID);
1307 
1308   // Allow targets to insert passes that improve instruction level parallelism,
1309   // like if-conversion. Such passes will typically need dominator trees and
1310   // loop info, just like LICM and CSE below.
1311   addILPOpts();
1312 
1313   addPass(&EarlyMachineLICMID);
1314   addPass(&MachineCSEID);
1315 
1316   addPass(&MachineSinkingID);
1317 
1318   addPass(&PeepholeOptimizerID);
1319   // Clean-up the dead code that may have been generated by peephole
1320   // rewriting.
1321   addPass(&DeadMachineInstructionElimID);
1322 }
1323 
1324 //===---------------------------------------------------------------------===//
1325 /// Register Allocation Pass Configuration
1326 //===---------------------------------------------------------------------===//
1327 
1328 bool TargetPassConfig::getOptimizeRegAlloc() const {
1329   switch (OptimizeRegAlloc) {
1330   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
1331   case cl::BOU_TRUE:  return true;
1332   case cl::BOU_FALSE: return false;
1333   }
1334   llvm_unreachable("Invalid optimize-regalloc state");
1335 }
1336 
1337 /// A dummy default pass factory indicates whether the register allocator is
1338 /// overridden on the command line.
1339 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
1340 
1341 static RegisterRegAlloc
1342 defaultRegAlloc("default",
1343                 "pick register allocator based on -O option",
1344                 useDefaultRegisterAllocator);
1345 
1346 static void initializeDefaultRegisterAllocatorOnce() {
1347   if (!RegisterRegAlloc::getDefault())
1348     RegisterRegAlloc::setDefault(RegAlloc);
1349 }
1350 
1351 /// Instantiate the default register allocator pass for this target for either
1352 /// the optimized or unoptimized allocation path. This will be added to the pass
1353 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
1354 /// in the optimized case.
1355 ///
1356 /// A target that uses the standard regalloc pass order for fast or optimized
1357 /// allocation may still override this for per-target regalloc
1358 /// selection. But -regalloc=... always takes precedence.
1359 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
1360   if (Optimized)
1361     return createGreedyRegisterAllocator();
1362   else
1363     return createFastRegisterAllocator();
1364 }
1365 
1366 /// Find and instantiate the register allocation pass requested by this target
1367 /// at the current optimization level.  Different register allocators are
1368 /// defined as separate passes because they may require different analysis.
1369 ///
1370 /// This helper ensures that the regalloc= option is always available,
1371 /// even for targets that override the default allocator.
1372 ///
1373 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
1374 /// this can be folded into addPass.
1375 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
1376   // Initialize the global default.
1377   llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
1378                   initializeDefaultRegisterAllocatorOnce);
1379 
1380   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
1381   if (Ctor != useDefaultRegisterAllocator)
1382     return Ctor();
1383 
1384   // With no -regalloc= override, ask the target for a regalloc pass.
1385   return createTargetRegisterAllocator(Optimized);
1386 }
1387 
1388 bool TargetPassConfig::addRegAssignAndRewriteFast() {
1389   if (RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator &&
1390       RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator)
1391     report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
1392 
1393   addPass(createRegAllocPass(false));
1394 
1395   // Allow targets to change the register assignments after
1396   // fast register allocation.
1397   addPostFastRegAllocRewrite();
1398   return true;
1399 }
1400 
1401 bool TargetPassConfig::addRegAssignAndRewriteOptimized() {
1402   // Add the selected register allocation pass.
1403   addPass(createRegAllocPass(true));
1404 
1405   // Allow targets to change the register assignments before rewriting.
1406   addPreRewrite();
1407 
1408   // Finally rewrite virtual registers.
1409   addPass(&VirtRegRewriterID);
1410 
1411   // Regalloc scoring for ML-driven eviction - noop except when learning a new
1412   // eviction policy.
1413   addPass(createRegAllocScoringPass());
1414   return true;
1415 }
1416 
1417 /// Return true if the default global register allocator is in use and
1418 /// has not be overriden on the command line with '-regalloc=...'
1419 bool TargetPassConfig::usingDefaultRegAlloc() const {
1420   return RegAlloc.getNumOccurrences() == 0;
1421 }
1422 
1423 /// Add the minimum set of target-independent passes that are required for
1424 /// register allocation. No coalescing or scheduling.
1425 void TargetPassConfig::addFastRegAlloc() {
1426   addPass(&PHIEliminationID);
1427   addPass(&TwoAddressInstructionPassID);
1428 
1429   addRegAssignAndRewriteFast();
1430 }
1431 
1432 /// Add standard target-independent passes that are tightly coupled with
1433 /// optimized register allocation, including coalescing, machine instruction
1434 /// scheduling, and register allocation itself.
1435 void TargetPassConfig::addOptimizedRegAlloc() {
1436   addPass(&DetectDeadLanesID);
1437 
1438   addPass(&ProcessImplicitDefsID);
1439 
1440   // LiveVariables currently requires pure SSA form.
1441   //
1442   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1443   // LiveVariables can be removed completely, and LiveIntervals can be directly
1444   // computed. (We still either need to regenerate kill flags after regalloc, or
1445   // preferably fix the scavenger to not depend on them).
1446   // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables.
1447   // When LiveVariables is removed this has to be removed/moved either.
1448   // Explicit addition of UnreachableMachineBlockElim allows stopping before or
1449   // after it with -stop-before/-stop-after.
1450   addPass(&UnreachableMachineBlockElimID);
1451   addPass(&LiveVariablesID);
1452 
1453   // Edge splitting is smarter with machine loop info.
1454   addPass(&MachineLoopInfoID);
1455   addPass(&PHIEliminationID);
1456 
1457   // Eventually, we want to run LiveIntervals before PHI elimination.
1458   if (EarlyLiveIntervals)
1459     addPass(&LiveIntervalsID);
1460 
1461   addPass(&TwoAddressInstructionPassID);
1462   addPass(&RegisterCoalescerID);
1463 
1464   // The machine scheduler may accidentally create disconnected components
1465   // when moving subregister definitions around, avoid this by splitting them to
1466   // separate vregs before. Splitting can also improve reg. allocation quality.
1467   addPass(&RenameIndependentSubregsID);
1468 
1469   // PreRA instruction scheduling.
1470   addPass(&MachineSchedulerID);
1471 
1472   if (addRegAssignAndRewriteOptimized()) {
1473     // Perform stack slot coloring and post-ra machine LICM.
1474     addPass(&StackSlotColoringID);
1475 
1476     // Allow targets to expand pseudo instructions depending on the choice of
1477     // registers before MachineCopyPropagation.
1478     addPostRewrite();
1479 
1480     // Copy propagate to forward register uses and try to eliminate COPYs that
1481     // were not coalesced.
1482     addPass(&MachineCopyPropagationID);
1483 
1484     // Run post-ra machine LICM to hoist reloads / remats.
1485     //
1486     // FIXME: can this move into MachineLateOptimization?
1487     addPass(&MachineLICMID);
1488   }
1489 }
1490 
1491 //===---------------------------------------------------------------------===//
1492 /// Post RegAlloc Pass Configuration
1493 //===---------------------------------------------------------------------===//
1494 
1495 /// Add passes that optimize machine instructions after register allocation.
1496 void TargetPassConfig::addMachineLateOptimization() {
1497   // Branch folding must be run after regalloc and prolog/epilog insertion.
1498   addPass(&BranchFolderPassID);
1499 
1500   // Tail duplication.
1501   // Note that duplicating tail just increases code size and degrades
1502   // performance for targets that require Structured Control Flow.
1503   // In addition it can also make CFG irreducible. Thus we disable it.
1504   if (!TM->requiresStructuredCFG())
1505     addPass(&TailDuplicateID);
1506 
1507   // Copy propagation.
1508   addPass(&MachineCopyPropagationID);
1509 }
1510 
1511 /// Add standard GC passes.
1512 bool TargetPassConfig::addGCPasses() {
1513   addPass(&GCMachineCodeAnalysisID);
1514   return true;
1515 }
1516 
1517 /// Add standard basic block placement passes.
1518 void TargetPassConfig::addBlockPlacement() {
1519   if (EnableFSDiscriminator) {
1520     addPass(createMIRAddFSDiscriminatorsPass(
1521         sampleprof::FSDiscriminatorPass::Pass2));
1522     const std::string ProfileFile = getFSProfileFile(TM);
1523     if (!ProfileFile.empty() && !DisableLayoutFSProfileLoader)
1524       addPass(
1525           createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM),
1526                                      sampleprof::FSDiscriminatorPass::Pass2));
1527   }
1528   if (addPass(&MachineBlockPlacementID)) {
1529     // Run a separate pass to collect block placement statistics.
1530     if (EnableBlockPlacementStats)
1531       addPass(&MachineBlockPlacementStatsID);
1532   }
1533 }
1534 
1535 //===---------------------------------------------------------------------===//
1536 /// GlobalISel Configuration
1537 //===---------------------------------------------------------------------===//
1538 bool TargetPassConfig::isGlobalISelAbortEnabled() const {
1539   return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable;
1540 }
1541 
1542 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
1543   return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag;
1544 }
1545 
1546 bool TargetPassConfig::isGISelCSEEnabled() const {
1547   return true;
1548 }
1549 
1550 std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const {
1551   return std::make_unique<CSEConfigBase>();
1552 }
1553