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