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