xref: /llvm-project/llvm/lib/CodeGen/TargetPassConfig.cpp (revision feffb0c8af00b975d678a364fff19c4ffb8bfd61)
1 //===- TargetPassConfig.cpp - Target independent code generation passes ---===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
12 //
13 //===---------------------------------------------------------------------===//
14 
15 #include "llvm/CodeGen/TargetPassConfig.h"
16 #include "llvm/ADT/DenseMap.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/StringRef.h"
19 #include "llvm/Analysis/BasicAliasAnalysis.h"
20 #include "llvm/Analysis/CFLAndersAliasAnalysis.h"
21 #include "llvm/Analysis/CFLSteensAliasAnalysis.h"
22 #include "llvm/Analysis/CallGraphSCCPass.h"
23 #include "llvm/Analysis/ScopedNoAliasAA.h"
24 #include "llvm/Analysis/TargetTransformInfo.h"
25 #include "llvm/Analysis/TypeBasedAliasAnalysis.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/Verifier.h"
33 #include "llvm/MC/MCAsmInfo.h"
34 #include "llvm/MC/MCTargetOptions.h"
35 #include "llvm/Pass.h"
36 #include "llvm/Support/CodeGen.h"
37 #include "llvm/Support/CommandLine.h"
38 #include "llvm/Support/Compiler.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/ErrorHandling.h"
41 #include "llvm/Support/Threading.h"
42 #include "llvm/Target/TargetMachine.h"
43 #include "llvm/Transforms/Scalar.h"
44 #include "llvm/Transforms/Utils/SymbolRewriter.h"
45 #include <cassert>
46 #include <string>
47 
48 using namespace llvm;
49 
50 cl::opt<bool> EnableIPRA("enable-ipra", cl::init(false), cl::Hidden,
51                          cl::desc("Enable interprocedural register allocation "
52                                   "to reduce load/store at procedure calls."));
53 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden,
54     cl::desc("Disable Post Regalloc Scheduler"));
55 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
56     cl::desc("Disable branch folding"));
57 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
58     cl::desc("Disable tail duplication"));
59 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
60     cl::desc("Disable pre-register allocation tail duplication"));
61 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
62     cl::Hidden, cl::desc("Disable probability-driven block placement"));
63 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
64     cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
65 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
66     cl::desc("Disable Stack Slot Coloring"));
67 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
68     cl::desc("Disable Machine Dead Code Elimination"));
69 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
70     cl::desc("Disable Early If-conversion"));
71 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
72     cl::desc("Disable Machine LICM"));
73 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
74     cl::desc("Disable Machine Common Subexpression Elimination"));
75 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc(
76     "optimize-regalloc", cl::Hidden,
77     cl::desc("Enable optimized register allocation compilation path."));
78 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
79     cl::Hidden,
80     cl::desc("Disable Machine LICM"));
81 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
82     cl::desc("Disable Machine Sinking"));
83 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
84     cl::desc("Disable Loop Strength Reduction Pass"));
85 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
86     cl::Hidden, cl::desc("Disable ConstantHoisting"));
87 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
88     cl::desc("Disable Codegen Prepare"));
89 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
90     cl::desc("Disable Copy Propagation pass"));
91 static cl::opt<bool> DisableCopyPropPreRegRewrite("disable-copyprop-prerewrite", cl::Hidden,
92     cl::desc("Disable Copy Propagation Pre-Register Re-write pass"));
93 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
94     cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
95 static cl::opt<bool> EnableImplicitNullChecks(
96     "enable-implicit-null-checks",
97     cl::desc("Fold null checks into faulting memory operations"),
98     cl::init(false));
99 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
100     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
101 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
102     cl::desc("Print LLVM IR input to isel pass"));
103 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
104     cl::desc("Dump garbage collector data"));
105 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
106     cl::desc("Verify generated machine code"),
107     cl::init(false),
108     cl::ZeroOrMore);
109 static cl::opt<bool> EnableMachineOutliner("enable-machine-outliner",
110     cl::Hidden,
111     cl::desc("Enable machine outliner"));
112 // Enable or disable FastISel. Both options are needed, because
113 // FastISel is enabled by default with -fast, and we wish to be
114 // able to enable or disable fast-isel independently from -O0.
115 static cl::opt<cl::boolOrDefault>
116 EnableFastISelOption("fast-isel", cl::Hidden,
117   cl::desc("Enable the \"fast\" instruction selector"));
118 
119 static cl::opt<cl::boolOrDefault>
120     EnableGlobalISel("global-isel", cl::Hidden,
121                      cl::desc("Enable the \"global\" instruction selector"));
122 
123 static cl::opt<std::string>
124 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
125                    cl::desc("Print machine instrs"),
126                    cl::value_desc("pass-name"), cl::init("option-unspecified"));
127 
128 static cl::opt<int> EnableGlobalISelAbort(
129     "global-isel-abort", cl::Hidden,
130     cl::desc("Enable abort calls when \"global\" instruction selection "
131              "fails to lower/select an instruction: 0 disable the abort, "
132              "1 enable the abort, and "
133              "2 disable the abort but emit a diagnostic on failure"),
134     cl::init(1));
135 
136 // Temporary option to allow experimenting with MachineScheduler as a post-RA
137 // scheduler. Targets can "properly" enable this with
138 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID).
139 // Targets can return true in targetSchedulesPostRAScheduling() and
140 // insert a PostRA scheduling pass wherever it wants.
141 cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
142   cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
143 
144 // Experimental option to run live interval analysis early.
145 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
146     cl::desc("Run live interval analysis earlier in the pipeline"));
147 
148 // Experimental option to use CFL-AA in codegen
149 enum class CFLAAType { None, Steensgaard, Andersen, Both };
150 static cl::opt<CFLAAType> UseCFLAA(
151     "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden,
152     cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"),
153     cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"),
154                clEnumValN(CFLAAType::Steensgaard, "steens",
155                           "Enable unification-based CFL-AA"),
156                clEnumValN(CFLAAType::Andersen, "anders",
157                           "Enable inclusion-based CFL-AA"),
158                clEnumValN(CFLAAType::Both, "both",
159                           "Enable both variants of CFL-AA")));
160 
161 /// Option names for limiting the codegen pipeline.
162 /// Those are used in error reporting and we didn't want
163 /// to duplicate their names all over the place.
164 const char *StartAfterOptName = "start-after";
165 const char *StartBeforeOptName = "start-before";
166 const char *StopAfterOptName = "stop-after";
167 const char *StopBeforeOptName = "stop-before";
168 
169 static cl::opt<std::string>
170     StartAfterOpt(StringRef(StartAfterOptName),
171                   cl::desc("Resume compilation after a specific pass"),
172                   cl::value_desc("pass-name"), cl::init(""));
173 
174 static cl::opt<std::string>
175     StartBeforeOpt(StringRef(StartBeforeOptName),
176                    cl::desc("Resume compilation before a specific pass"),
177                    cl::value_desc("pass-name"), cl::init(""));
178 
179 static cl::opt<std::string>
180     StopAfterOpt(StringRef(StopAfterOptName),
181                  cl::desc("Stop compilation after a specific pass"),
182                  cl::value_desc("pass-name"), cl::init(""));
183 
184 static cl::opt<std::string>
185     StopBeforeOpt(StringRef(StopBeforeOptName),
186                   cl::desc("Stop compilation before a specific pass"),
187                   cl::value_desc("pass-name"), cl::init(""));
188 
189 /// Allow standard passes to be disabled by command line options. This supports
190 /// simple binary flags that either suppress the pass or do nothing.
191 /// i.e. -disable-mypass=false has no effect.
192 /// These should be converted to boolOrDefault in order to use applyOverride.
193 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
194                                        bool Override) {
195   if (Override)
196     return IdentifyingPassPtr();
197   return PassID;
198 }
199 
200 /// Allow standard passes to be disabled by the command line, regardless of who
201 /// is adding the pass.
202 ///
203 /// StandardID is the pass identified in the standard pass pipeline and provided
204 /// to addPass(). It may be a target-specific ID in the case that the target
205 /// directly adds its own pass, but in that case we harmlessly fall through.
206 ///
207 /// TargetID is the pass that the target has configured to override StandardID.
208 ///
209 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
210 /// pass to run. This allows multiple options to control a single pass depending
211 /// on where in the pipeline that pass is added.
212 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
213                                        IdentifyingPassPtr TargetID) {
214   if (StandardID == &PostRASchedulerID)
215     return applyDisable(TargetID, DisablePostRASched);
216 
217   if (StandardID == &BranchFolderPassID)
218     return applyDisable(TargetID, DisableBranchFold);
219 
220   if (StandardID == &TailDuplicateID)
221     return applyDisable(TargetID, DisableTailDuplicate);
222 
223   if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
224     return applyDisable(TargetID, DisableEarlyTailDup);
225 
226   if (StandardID == &MachineBlockPlacementID)
227     return applyDisable(TargetID, DisableBlockPlacement);
228 
229   if (StandardID == &StackSlotColoringID)
230     return applyDisable(TargetID, DisableSSC);
231 
232   if (StandardID == &DeadMachineInstructionElimID)
233     return applyDisable(TargetID, DisableMachineDCE);
234 
235   if (StandardID == &EarlyIfConverterID)
236     return applyDisable(TargetID, DisableEarlyIfConversion);
237 
238   if (StandardID == &MachineLICMID)
239     return applyDisable(TargetID, DisableMachineLICM);
240 
241   if (StandardID == &MachineCSEID)
242     return applyDisable(TargetID, DisableMachineCSE);
243 
244   if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
245     return applyDisable(TargetID, DisablePostRAMachineLICM);
246 
247   if (StandardID == &MachineSinkingID)
248     return applyDisable(TargetID, DisableMachineSink);
249 
250   if (StandardID == &MachineCopyPropagationID)
251     return applyDisable(TargetID, DisableCopyProp);
252 
253   if (StandardID == &MachineCopyPropagationPreRegRewriteID)
254     return applyDisable(TargetID, DisableCopyPropPreRegRewrite);
255 
256   return TargetID;
257 }
258 
259 //===---------------------------------------------------------------------===//
260 /// TargetPassConfig
261 //===---------------------------------------------------------------------===//
262 
263 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
264                 "Target Pass Configuration", false, false)
265 char TargetPassConfig::ID = 0;
266 
267 // Pseudo Pass IDs.
268 char TargetPassConfig::EarlyTailDuplicateID = 0;
269 char TargetPassConfig::PostRAMachineLICMID = 0;
270 
271 namespace {
272 
273 struct InsertedPass {
274   AnalysisID TargetPassID;
275   IdentifyingPassPtr InsertedPassID;
276   bool VerifyAfter;
277   bool PrintAfter;
278 
279   InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID,
280                bool VerifyAfter, bool PrintAfter)
281       : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID),
282         VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {}
283 
284   Pass *getInsertedPass() const {
285     assert(InsertedPassID.isValid() && "Illegal Pass ID!");
286     if (InsertedPassID.isInstance())
287       return InsertedPassID.getInstance();
288     Pass *NP = Pass::createPass(InsertedPassID.getID());
289     assert(NP && "Pass ID not registered");
290     return NP;
291   }
292 };
293 
294 } // end anonymous namespace
295 
296 namespace llvm {
297 
298 class PassConfigImpl {
299 public:
300   // List of passes explicitly substituted by this target. Normally this is
301   // empty, but it is a convenient way to suppress or replace specific passes
302   // that are part of a standard pass pipeline without overridding the entire
303   // pipeline. This mechanism allows target options to inherit a standard pass's
304   // user interface. For example, a target may disable a standard pass by
305   // default by substituting a pass ID of zero, and the user may still enable
306   // that standard pass with an explicit command line option.
307   DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
308 
309   /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
310   /// is inserted after each instance of the first one.
311   SmallVector<InsertedPass, 4> InsertedPasses;
312 };
313 
314 } // end namespace llvm
315 
316 // Out of line virtual method.
317 TargetPassConfig::~TargetPassConfig() {
318   delete Impl;
319 }
320 
321 static const PassInfo *getPassInfo(StringRef PassName) {
322   if (PassName.empty())
323     return nullptr;
324 
325   const PassRegistry &PR = *PassRegistry::getPassRegistry();
326   const PassInfo *PI = PR.getPassInfo(PassName);
327   if (!PI)
328     report_fatal_error(Twine('\"') + Twine(PassName) +
329                        Twine("\" pass is not registered."));
330   return PI;
331 }
332 
333 static AnalysisID getPassIDFromName(StringRef PassName) {
334   const PassInfo *PI = getPassInfo(PassName);
335   return PI ? PI->getTypeInfo() : nullptr;
336 }
337 
338 void TargetPassConfig::setStartStopPasses() {
339   StartBefore = getPassIDFromName(StartBeforeOpt);
340   StartAfter = getPassIDFromName(StartAfterOpt);
341   StopBefore = getPassIDFromName(StopBeforeOpt);
342   StopAfter = getPassIDFromName(StopAfterOpt);
343   if (StartBefore && StartAfter)
344     report_fatal_error(Twine(StartBeforeOptName) + Twine(" and ") +
345                        Twine(StartAfterOptName) + Twine(" specified!"));
346   if (StopBefore && StopAfter)
347     report_fatal_error(Twine(StopBeforeOptName) + Twine(" and ") +
348                        Twine(StopAfterOptName) + Twine(" specified!"));
349   Started = (StartAfter == nullptr) && (StartBefore == nullptr);
350 }
351 
352 // Out of line constructor provides default values for pass options and
353 // registers all common codegen passes.
354 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm)
355     : ImmutablePass(ID), PM(&pm), TM(&TM) {
356   Impl = new PassConfigImpl();
357 
358   // Register all target independent codegen passes to activate their PassIDs,
359   // including this pass itself.
360   initializeCodeGen(*PassRegistry::getPassRegistry());
361 
362   // Also register alias analysis passes required by codegen passes.
363   initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry());
364   initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry());
365 
366   // Substitute Pseudo Pass IDs for real ones.
367   substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
368   substitutePass(&PostRAMachineLICMID, &MachineLICMID);
369 
370   if (StringRef(PrintMachineInstrs.getValue()).equals(""))
371     TM.Options.PrintMachineCode = true;
372 
373   if (EnableIPRA.getNumOccurrences())
374     TM.Options.EnableIPRA = EnableIPRA;
375   else {
376     // If not explicitly specified, use target default.
377     TM.Options.EnableIPRA = TM.useIPRA();
378   }
379 
380   if (TM.Options.EnableIPRA)
381     setRequiresCodeGenSCCOrder();
382 
383   setStartStopPasses();
384 }
385 
386 CodeGenOpt::Level TargetPassConfig::getOptLevel() const {
387   return TM->getOptLevel();
388 }
389 
390 /// Insert InsertedPassID pass after TargetPassID.
391 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
392                                   IdentifyingPassPtr InsertedPassID,
393                                   bool VerifyAfter, bool PrintAfter) {
394   assert(((!InsertedPassID.isInstance() &&
395            TargetPassID != InsertedPassID.getID()) ||
396           (InsertedPassID.isInstance() &&
397            TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
398          "Insert a pass after itself!");
399   Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter,
400                                     PrintAfter);
401 }
402 
403 /// createPassConfig - Create a pass configuration object to be used by
404 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
405 ///
406 /// Targets may override this to extend TargetPassConfig.
407 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
408   return new TargetPassConfig(*this, PM);
409 }
410 
411 TargetPassConfig::TargetPassConfig()
412   : ImmutablePass(ID) {
413   report_fatal_error("Trying to construct TargetPassConfig without a target "
414                      "machine. Scheduling a CodeGen pass without a target "
415                      "triple set?");
416 }
417 
418 bool TargetPassConfig::hasLimitedCodeGenPipeline() const {
419   return StartBefore || StartAfter || StopBefore || StopAfter;
420 }
421 
422 std::string
423 TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) const {
424   if (!hasLimitedCodeGenPipeline())
425     return std::string();
426   std::string Res;
427   static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt,
428                                               &StopAfterOpt, &StopBeforeOpt};
429   static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName,
430                                    StopAfterOptName, StopBeforeOptName};
431   bool IsFirst = true;
432   for (int Idx = 0; Idx < 4; ++Idx)
433     if (!PassNames[Idx]->empty()) {
434       if (!IsFirst)
435         Res += Separator;
436       IsFirst = false;
437       Res += OptNames[Idx];
438     }
439   return Res;
440 }
441 
442 // Helper to verify the analysis is really immutable.
443 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
444   assert(!Initialized && "PassConfig is immutable");
445   Opt = Val;
446 }
447 
448 void TargetPassConfig::substitutePass(AnalysisID StandardID,
449                                       IdentifyingPassPtr TargetID) {
450   Impl->TargetPasses[StandardID] = TargetID;
451 }
452 
453 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
454   DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
455     I = Impl->TargetPasses.find(ID);
456   if (I == Impl->TargetPasses.end())
457     return ID;
458   return I->second;
459 }
460 
461 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const {
462   IdentifyingPassPtr TargetID = getPassSubstitution(ID);
463   IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID);
464   return !FinalPtr.isValid() || FinalPtr.isInstance() ||
465       FinalPtr.getID() != ID;
466 }
467 
468 /// Add a pass to the PassManager if that pass is supposed to be run.  If the
469 /// Started/Stopped flags indicate either that the compilation should start at
470 /// a later pass or that it should stop after an earlier pass, then do not add
471 /// the pass.  Finally, compare the current pass against the StartAfter
472 /// and StopAfter options and change the Started/Stopped flags accordingly.
473 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
474   assert(!Initialized && "PassConfig is immutable");
475 
476   // Cache the Pass ID here in case the pass manager finds this pass is
477   // redundant with ones already scheduled / available, and deletes it.
478   // Fundamentally, once we add the pass to the manager, we no longer own it
479   // and shouldn't reference it.
480   AnalysisID PassID = P->getPassID();
481 
482   if (StartBefore == PassID)
483     Started = true;
484   if (StopBefore == PassID)
485     Stopped = true;
486   if (Started && !Stopped) {
487     std::string Banner;
488     // Construct banner message before PM->add() as that may delete the pass.
489     if (AddingMachinePasses && (printAfter || verifyAfter))
490       Banner = std::string("After ") + std::string(P->getPassName());
491     PM->add(P);
492     if (AddingMachinePasses) {
493       if (printAfter)
494         addPrintPass(Banner);
495       if (verifyAfter)
496         addVerifyPass(Banner);
497     }
498 
499     // Add the passes after the pass P if there is any.
500     for (auto IP : Impl->InsertedPasses) {
501       if (IP.TargetPassID == PassID)
502         addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter);
503     }
504   } else {
505     delete P;
506   }
507   if (StopAfter == PassID)
508     Stopped = true;
509   if (StartAfter == PassID)
510     Started = true;
511   if (Stopped && !Started)
512     report_fatal_error("Cannot stop compilation after pass that is not run");
513 }
514 
515 /// Add a CodeGen pass at this point in the pipeline after checking for target
516 /// and command line overrides.
517 ///
518 /// addPass cannot return a pointer to the pass instance because is internal the
519 /// PassManager and the instance we create here may already be freed.
520 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
521                                      bool printAfter) {
522   IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
523   IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
524   if (!FinalPtr.isValid())
525     return nullptr;
526 
527   Pass *P;
528   if (FinalPtr.isInstance())
529     P = FinalPtr.getInstance();
530   else {
531     P = Pass::createPass(FinalPtr.getID());
532     if (!P)
533       llvm_unreachable("Pass ID not registered");
534   }
535   AnalysisID FinalID = P->getPassID();
536   addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
537 
538   return FinalID;
539 }
540 
541 void TargetPassConfig::printAndVerify(const std::string &Banner) {
542   addPrintPass(Banner);
543   addVerifyPass(Banner);
544 }
545 
546 void TargetPassConfig::addPrintPass(const std::string &Banner) {
547   if (TM->shouldPrintMachineCode())
548     PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
549 }
550 
551 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
552   bool Verify = VerifyMachineCode;
553 #ifdef EXPENSIVE_CHECKS
554   if (VerifyMachineCode == cl::BOU_UNSET)
555     Verify = TM->isMachineVerifierClean();
556 #endif
557   if (Verify)
558     PM->add(createMachineVerifierPass(Banner));
559 }
560 
561 /// Add common target configurable passes that perform LLVM IR to IR transforms
562 /// following machine independent optimization.
563 void TargetPassConfig::addIRPasses() {
564   switch (UseCFLAA) {
565   case CFLAAType::Steensgaard:
566     addPass(createCFLSteensAAWrapperPass());
567     break;
568   case CFLAAType::Andersen:
569     addPass(createCFLAndersAAWrapperPass());
570     break;
571   case CFLAAType::Both:
572     addPass(createCFLAndersAAWrapperPass());
573     addPass(createCFLSteensAAWrapperPass());
574     break;
575   default:
576     break;
577   }
578 
579   // Basic AliasAnalysis support.
580   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
581   // BasicAliasAnalysis wins if they disagree. This is intended to help
582   // support "obvious" type-punning idioms.
583   addPass(createTypeBasedAAWrapperPass());
584   addPass(createScopedNoAliasAAWrapperPass());
585   addPass(createBasicAAWrapperPass());
586 
587   // Before running any passes, run the verifier to determine if the input
588   // coming from the front-end and/or optimizer is valid.
589   if (!DisableVerify)
590     addPass(createVerifierPass());
591 
592   // Run loop strength reduction before anything else.
593   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
594     addPass(createLoopStrengthReducePass());
595     if (PrintLSR)
596       addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
597   }
598 
599   // Run GC lowering passes for builtin collectors
600   // TODO: add a pass insertion point here
601   addPass(createGCLoweringPass());
602   addPass(createShadowStackGCLoweringPass());
603 
604   // Make sure that no unreachable blocks are instruction selected.
605   addPass(createUnreachableBlockEliminationPass());
606 
607   // Prepare expensive constants for SelectionDAG.
608   if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
609     addPass(createConstantHoistingPass());
610 
611   if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
612     addPass(createPartiallyInlineLibCallsPass());
613 
614   // Insert calls to mcount-like functions.
615   addPass(createCountingFunctionInserterPass());
616 
617   // Add scalarization of target's unsupported masked memory intrinsics pass.
618   // the unsupported intrinsic will be replaced with a chain of basic blocks,
619   // that stores/loads element one-by-one if the appropriate mask bit is set.
620   addPass(createScalarizeMaskedMemIntrinPass());
621 
622   // Expand reduction intrinsics into shuffle sequences if the target wants to.
623   addPass(createExpandReductionsPass());
624 }
625 
626 /// Turn exception handling constructs into something the code generators can
627 /// handle.
628 void TargetPassConfig::addPassesToHandleExceptions() {
629   const MCAsmInfo *MCAI = TM->getMCAsmInfo();
630   assert(MCAI && "No MCAsmInfo");
631   switch (MCAI->getExceptionHandlingType()) {
632   case ExceptionHandling::SjLj:
633     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
634     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
635     // catch info can get misplaced when a selector ends up more than one block
636     // removed from the parent invoke(s). This could happen when a landing
637     // pad is shared by multiple invokes and is also a target of a normal
638     // edge from elsewhere.
639     addPass(createSjLjEHPreparePass());
640     LLVM_FALLTHROUGH;
641   case ExceptionHandling::DwarfCFI:
642   case ExceptionHandling::ARM:
643     addPass(createDwarfEHPass());
644     break;
645   case ExceptionHandling::WinEH:
646     // We support using both GCC-style and MSVC-style exceptions on Windows, so
647     // add both preparation passes. Each pass will only actually run if it
648     // recognizes the personality function.
649     addPass(createWinEHPass());
650     addPass(createDwarfEHPass());
651     break;
652   case ExceptionHandling::None:
653     addPass(createLowerInvokePass());
654 
655     // The lower invoke pass may create unreachable code. Remove it.
656     addPass(createUnreachableBlockEliminationPass());
657     break;
658   }
659 }
660 
661 /// Add pass to prepare the LLVM IR for code generation. This should be done
662 /// before exception handling preparation passes.
663 void TargetPassConfig::addCodeGenPrepare() {
664   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
665     addPass(createCodeGenPreparePass());
666   addPass(createRewriteSymbolsPass());
667 }
668 
669 /// Add common passes that perform LLVM IR to IR transforms in preparation for
670 /// instruction selection.
671 void TargetPassConfig::addISelPrepare() {
672   addPreISel();
673 
674   // Force codegen to run according to the callgraph.
675   if (requiresCodeGenSCCOrder())
676     addPass(new DummyCGSCCPass);
677 
678   // Add both the safe stack and the stack protection passes: each of them will
679   // only protect functions that have corresponding attributes.
680   addPass(createSafeStackPass());
681   addPass(createStackProtectorPass());
682 
683   if (PrintISelInput)
684     addPass(createPrintFunctionPass(
685         dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
686 
687   // All passes which modify the LLVM IR are now complete; run the verifier
688   // to ensure that the IR is valid.
689   if (!DisableVerify)
690     addPass(createVerifierPass());
691 }
692 
693 bool TargetPassConfig::addCoreISelPasses() {
694   // Enable FastISel with -fast, but allow that to be overridden.
695   TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE);
696   if (EnableFastISelOption == cl::BOU_TRUE ||
697       (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel()))
698     TM->setFastISel(true);
699 
700   // Ask the target for an isel.
701   // Enable GlobalISel if the target wants to, but allow that to be overriden.
702   if (EnableGlobalISel == cl::BOU_TRUE ||
703       (EnableGlobalISel == cl::BOU_UNSET && isGlobalISelEnabled())) {
704     if (addIRTranslator())
705       return true;
706 
707     addPreLegalizeMachineIR();
708 
709     if (addLegalizeMachineIR())
710       return true;
711 
712     // Before running the register bank selector, ask the target if it
713     // wants to run some passes.
714     addPreRegBankSelect();
715 
716     if (addRegBankSelect())
717       return true;
718 
719     addPreGlobalInstructionSelect();
720 
721     if (addGlobalInstructionSelect())
722       return true;
723 
724     // Pass to reset the MachineFunction if the ISel failed.
725     addPass(createResetMachineFunctionPass(
726         reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled()));
727 
728     // Provide a fallback path when we do not want to abort on
729     // not-yet-supported input.
730     if (!isGlobalISelAbortEnabled() && addInstSelector())
731       return true;
732 
733   } else if (addInstSelector())
734     return true;
735 
736   return false;
737 }
738 
739 bool TargetPassConfig::addISelPasses() {
740   if (TM->Options.EmulatedTLS)
741     addPass(createLowerEmuTLSPass());
742 
743   addPass(createPreISelIntrinsicLoweringPass());
744   addPass(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis()));
745   addIRPasses();
746   addCodeGenPrepare();
747   addPassesToHandleExceptions();
748   addISelPrepare();
749 
750   return addCoreISelPasses();
751 }
752 
753 /// -regalloc=... command line option.
754 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
755 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
756                RegisterPassParser<RegisterRegAlloc> >
757 RegAlloc("regalloc",
758          cl::init(&useDefaultRegisterAllocator),
759          cl::desc("Register allocator to use"));
760 
761 /// Add the complete set of target-independent postISel code generator passes.
762 ///
763 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
764 /// with nontrivial configuration or multiple passes are broken out below in
765 /// add%Stage routines.
766 ///
767 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
768 /// addPre/Post methods with empty header implementations allow injecting
769 /// target-specific fixups just before or after major stages. Additionally,
770 /// targets have the flexibility to change pass order within a stage by
771 /// overriding default implementation of add%Stage routines below. Each
772 /// technique has maintainability tradeoffs because alternate pass orders are
773 /// not well supported. addPre/Post works better if the target pass is easily
774 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
775 /// the target should override the stage instead.
776 ///
777 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
778 /// before/after any target-independent pass. But it's currently overkill.
779 void TargetPassConfig::addMachinePasses() {
780   AddingMachinePasses = true;
781 
782   // Insert a machine instr printer pass after the specified pass.
783   if (!StringRef(PrintMachineInstrs.getValue()).equals("") &&
784       !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) {
785     const PassRegistry *PR = PassRegistry::getPassRegistry();
786     const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
787     const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
788     assert (TPI && IPI && "Pass ID not registered!");
789     const char *TID = (const char *)(TPI->getTypeInfo());
790     const char *IID = (const char *)(IPI->getTypeInfo());
791     insertPass(TID, IID);
792   }
793 
794   // Print the instruction selected machine code...
795   printAndVerify("After Instruction Selection");
796 
797   // Expand pseudo-instructions emitted by ISel.
798   addPass(&ExpandISelPseudosID);
799 
800   // Add passes that optimize machine instructions in SSA form.
801   if (getOptLevel() != CodeGenOpt::None) {
802     addMachineSSAOptimization();
803   } else {
804     // If the target requests it, assign local variables to stack slots relative
805     // to one another and simplify frame index references where possible.
806     addPass(&LocalStackSlotAllocationID, false);
807   }
808 
809   if (TM->Options.EnableIPRA)
810     addPass(createRegUsageInfoPropPass());
811 
812   // Run pre-ra passes.
813   addPreRegAlloc();
814 
815   // Run register allocation and passes that are tightly coupled with it,
816   // including phi elimination and scheduling.
817   if (getOptimizeRegAlloc())
818     addOptimizedRegAlloc(createRegAllocPass(true));
819   else {
820     if (RegAlloc != &useDefaultRegisterAllocator &&
821         RegAlloc != &createFastRegisterAllocator)
822       report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc.");
823     addFastRegAlloc(createRegAllocPass(false));
824   }
825 
826   // Run post-ra passes.
827   addPostRegAlloc();
828 
829   // Insert prolog/epilog code.  Eliminate abstract frame index references...
830   if (getOptLevel() != CodeGenOpt::None)
831     addPass(&ShrinkWrapID);
832 
833   // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only
834   // do so if it hasn't been disabled, substituted, or overridden.
835   if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID))
836       addPass(createPrologEpilogInserterPass());
837 
838   /// Add passes that optimize machine instructions after register allocation.
839   if (getOptLevel() != CodeGenOpt::None)
840     addMachineLateOptimization();
841 
842   // Expand pseudo instructions before second scheduling pass.
843   addPass(&ExpandPostRAPseudosID);
844 
845   // Run pre-sched2 passes.
846   addPreSched2();
847 
848   if (EnableImplicitNullChecks)
849     addPass(&ImplicitNullChecksID);
850 
851   // Second pass scheduler.
852   // Let Target optionally insert this pass by itself at some other
853   // point.
854   if (getOptLevel() != CodeGenOpt::None &&
855       !TM->targetSchedulesPostRAScheduling()) {
856     if (MISchedPostRA)
857       addPass(&PostMachineSchedulerID);
858     else
859       addPass(&PostRASchedulerID);
860   }
861 
862   // GC
863   if (addGCPasses()) {
864     if (PrintGCInfo)
865       addPass(createGCInfoPrinter(dbgs()), false, false);
866   }
867 
868   // Basic block placement.
869   if (getOptLevel() != CodeGenOpt::None)
870     addBlockPlacement();
871 
872   addPreEmitPass();
873 
874   if (TM->Options.EnableIPRA)
875     // Collect register usage information and produce a register mask of
876     // clobbered registers, to be used to optimize call sites.
877     addPass(createRegUsageInfoCollector());
878 
879   addPass(&FuncletLayoutID, false);
880 
881   addPass(&StackMapLivenessID, false);
882   addPass(&LiveDebugValuesID, false);
883 
884   // Insert before XRay Instrumentation.
885   addPass(&FEntryInserterID, false);
886 
887   addPass(&XRayInstrumentationID, false);
888   addPass(&PatchableFunctionID, false);
889 
890   if (EnableMachineOutliner)
891     PM->add(createMachineOutlinerPass());
892 
893   AddingMachinePasses = false;
894 }
895 
896 /// Add passes that optimize machine instructions in SSA form.
897 void TargetPassConfig::addMachineSSAOptimization() {
898   // Pre-ra tail duplication.
899   addPass(&EarlyTailDuplicateID);
900 
901   // Optimize PHIs before DCE: removing dead PHI cycles may make more
902   // instructions dead.
903   addPass(&OptimizePHIsID, false);
904 
905   // This pass merges large allocas. StackSlotColoring is a different pass
906   // which merges spill slots.
907   addPass(&StackColoringID, false);
908 
909   // If the target requests it, assign local variables to stack slots relative
910   // to one another and simplify frame index references where possible.
911   addPass(&LocalStackSlotAllocationID, false);
912 
913   // With optimization, dead code should already be eliminated. However
914   // there is one known exception: lowered code for arguments that are only
915   // used by tail calls, where the tail calls reuse the incoming stack
916   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
917   addPass(&DeadMachineInstructionElimID);
918 
919   // Allow targets to insert passes that improve instruction level parallelism,
920   // like if-conversion. Such passes will typically need dominator trees and
921   // loop info, just like LICM and CSE below.
922   addILPOpts();
923 
924   addPass(&MachineLICMID, false);
925   addPass(&MachineCSEID, false);
926 
927   addPass(&MachineSinkingID);
928 
929   addPass(&PeepholeOptimizerID);
930   // Clean-up the dead code that may have been generated by peephole
931   // rewriting.
932   addPass(&DeadMachineInstructionElimID);
933 }
934 
935 //===---------------------------------------------------------------------===//
936 /// Register Allocation Pass Configuration
937 //===---------------------------------------------------------------------===//
938 
939 bool TargetPassConfig::getOptimizeRegAlloc() const {
940   switch (OptimizeRegAlloc) {
941   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
942   case cl::BOU_TRUE:  return true;
943   case cl::BOU_FALSE: return false;
944   }
945   llvm_unreachable("Invalid optimize-regalloc state");
946 }
947 
948 /// RegisterRegAlloc's global Registry tracks allocator registration.
949 MachinePassRegistry RegisterRegAlloc::Registry;
950 
951 /// A dummy default pass factory indicates whether the register allocator is
952 /// overridden on the command line.
953 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag;
954 
955 static RegisterRegAlloc
956 defaultRegAlloc("default",
957                 "pick register allocator based on -O option",
958                 useDefaultRegisterAllocator);
959 
960 static void initializeDefaultRegisterAllocatorOnce() {
961   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
962 
963   if (!Ctor) {
964     Ctor = RegAlloc;
965     RegisterRegAlloc::setDefault(RegAlloc);
966   }
967 }
968 
969 /// Instantiate the default register allocator pass for this target for either
970 /// the optimized or unoptimized allocation path. This will be added to the pass
971 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
972 /// in the optimized case.
973 ///
974 /// A target that uses the standard regalloc pass order for fast or optimized
975 /// allocation may still override this for per-target regalloc
976 /// selection. But -regalloc=... always takes precedence.
977 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
978   if (Optimized)
979     return createGreedyRegisterAllocator();
980   else
981     return createFastRegisterAllocator();
982 }
983 
984 /// Find and instantiate the register allocation pass requested by this target
985 /// at the current optimization level.  Different register allocators are
986 /// defined as separate passes because they may require different analysis.
987 ///
988 /// This helper ensures that the regalloc= option is always available,
989 /// even for targets that override the default allocator.
990 ///
991 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
992 /// this can be folded into addPass.
993 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
994   // Initialize the global default.
995   llvm::call_once(InitializeDefaultRegisterAllocatorFlag,
996                   initializeDefaultRegisterAllocatorOnce);
997 
998   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
999   if (Ctor != useDefaultRegisterAllocator)
1000     return Ctor();
1001 
1002   // With no -regalloc= override, ask the target for a regalloc pass.
1003   return createTargetRegisterAllocator(Optimized);
1004 }
1005 
1006 /// Return true if the default global register allocator is in use and
1007 /// has not be overriden on the command line with '-regalloc=...'
1008 bool TargetPassConfig::usingDefaultRegAlloc() const {
1009   return RegAlloc.getNumOccurrences() == 0;
1010 }
1011 
1012 /// Add the minimum set of target-independent passes that are required for
1013 /// register allocation. No coalescing or scheduling.
1014 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
1015   addPass(&PHIEliminationID, false);
1016   addPass(&TwoAddressInstructionPassID, false);
1017 
1018   if (RegAllocPass)
1019     addPass(RegAllocPass);
1020 }
1021 
1022 /// Add standard target-independent passes that are tightly coupled with
1023 /// optimized register allocation, including coalescing, machine instruction
1024 /// scheduling, and register allocation itself.
1025 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
1026   addPass(&DetectDeadLanesID, false);
1027 
1028   addPass(&ProcessImplicitDefsID, false);
1029 
1030   // LiveVariables currently requires pure SSA form.
1031   //
1032   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
1033   // LiveVariables can be removed completely, and LiveIntervals can be directly
1034   // computed. (We still either need to regenerate kill flags after regalloc, or
1035   // preferably fix the scavenger to not depend on them).
1036   addPass(&LiveVariablesID, false);
1037 
1038   // Edge splitting is smarter with machine loop info.
1039   addPass(&MachineLoopInfoID, false);
1040   addPass(&PHIEliminationID, false);
1041 
1042   // Eventually, we want to run LiveIntervals before PHI elimination.
1043   if (EarlyLiveIntervals)
1044     addPass(&LiveIntervalsID, false);
1045 
1046   addPass(&TwoAddressInstructionPassID, false);
1047   addPass(&RegisterCoalescerID);
1048 
1049   // The machine scheduler may accidentally create disconnected components
1050   // when moving subregister definitions around, avoid this by splitting them to
1051   // separate vregs before. Splitting can also improve reg. allocation quality.
1052   addPass(&RenameIndependentSubregsID);
1053 
1054   // PreRA instruction scheduling.
1055   addPass(&MachineSchedulerID);
1056 
1057   if (RegAllocPass) {
1058     // Add the selected register allocation pass.
1059     addPass(RegAllocPass);
1060 
1061     // Allow targets to change the register assignments before rewriting.
1062     addPreRewrite();
1063 
1064     // Copy propagate to forward register uses and try to eliminate COPYs that
1065     // were not coalesced.
1066     addPass(&MachineCopyPropagationPreRegRewriteID);
1067 
1068     // Finally rewrite virtual registers.
1069     addPass(&VirtRegRewriterID);
1070 
1071     // Perform stack slot coloring and post-ra machine LICM.
1072     //
1073     // FIXME: Re-enable coloring with register when it's capable of adding
1074     // kill markers.
1075     addPass(&StackSlotColoringID);
1076 
1077     // Run post-ra machine LICM to hoist reloads / remats.
1078     //
1079     // FIXME: can this move into MachineLateOptimization?
1080     addPass(&PostRAMachineLICMID);
1081   }
1082 }
1083 
1084 //===---------------------------------------------------------------------===//
1085 /// Post RegAlloc Pass Configuration
1086 //===---------------------------------------------------------------------===//
1087 
1088 /// Add passes that optimize machine instructions after register allocation.
1089 void TargetPassConfig::addMachineLateOptimization() {
1090   // Branch folding must be run after regalloc and prolog/epilog insertion.
1091   addPass(&BranchFolderPassID);
1092 
1093   // Tail duplication.
1094   // Note that duplicating tail just increases code size and degrades
1095   // performance for targets that require Structured Control Flow.
1096   // In addition it can also make CFG irreducible. Thus we disable it.
1097   if (!TM->requiresStructuredCFG())
1098     addPass(&TailDuplicateID);
1099 
1100   // Copy propagation.
1101   addPass(&MachineCopyPropagationID);
1102 }
1103 
1104 /// Add standard GC passes.
1105 bool TargetPassConfig::addGCPasses() {
1106   addPass(&GCMachineCodeAnalysisID, false);
1107   return true;
1108 }
1109 
1110 /// Add standard basic block placement passes.
1111 void TargetPassConfig::addBlockPlacement() {
1112   if (addPass(&MachineBlockPlacementID)) {
1113     // Run a separate pass to collect block placement statistics.
1114     if (EnableBlockPlacementStats)
1115       addPass(&MachineBlockPlacementStatsID);
1116   }
1117 }
1118 
1119 //===---------------------------------------------------------------------===//
1120 /// GlobalISel Configuration
1121 //===---------------------------------------------------------------------===//
1122 
1123 bool TargetPassConfig::isGlobalISelEnabled() const {
1124   return false;
1125 }
1126 
1127 bool TargetPassConfig::isGlobalISelAbortEnabled() const {
1128   return EnableGlobalISelAbort == 1;
1129 }
1130 
1131 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const {
1132   return EnableGlobalISelAbort == 2;
1133 }
1134