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