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