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