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