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