6e86c8f21099f7b748aa3b612fcc0ab22dc89d0c
[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(createBasicAliasAnalysisPass());
381
382   // Before running any passes, run the verifier to determine if the input
383   // coming from the front-end and/or optimizer is valid.
384   if (!DisableVerify) {
385     addPass(createVerifierPass());
386     addPass(createDebugInfoVerifierPass());
387   }
388
389   // Run loop strength reduction before anything else.
390   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
391     addPass(createLoopStrengthReducePass());
392     if (PrintLSR)
393       addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
394   }
395
396   addPass(createGCLoweringPass());
397
398   // Make sure that no unreachable blocks are instruction selected.
399   addPass(createUnreachableBlockEliminationPass());
400
401   // Prepare expensive constants for SelectionDAG.
402   if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
403     addPass(createConstantHoistingPass());
404
405   if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
406     addPass(createPartiallyInlineLibCallsPass());
407 }
408
409 /// Turn exception handling constructs into something the code generators can
410 /// handle.
411 void TargetPassConfig::addPassesToHandleExceptions() {
412   switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
413   case ExceptionHandling::SjLj:
414     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
415     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
416     // catch info can get misplaced when a selector ends up more than one block
417     // removed from the parent invoke(s). This could happen when a landing
418     // pad is shared by multiple invokes and is also a target of a normal
419     // edge from elsewhere.
420     addPass(createSjLjEHPreparePass(TM));
421     // FALLTHROUGH
422   case ExceptionHandling::DwarfCFI:
423   case ExceptionHandling::ARM:
424   case ExceptionHandling::WinEH:
425     addPass(createDwarfEHPass(TM));
426     break;
427   case ExceptionHandling::None:
428     addPass(createLowerInvokePass());
429
430     // The lower invoke pass may create unreachable code. Remove it.
431     addPass(createUnreachableBlockEliminationPass());
432     break;
433   }
434 }
435
436 /// Add pass to prepare the LLVM IR for code generation. This should be done
437 /// before exception handling preparation passes.
438 void TargetPassConfig::addCodeGenPrepare() {
439   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
440     addPass(createCodeGenPreparePass(TM));
441 }
442
443 /// Add common passes that perform LLVM IR to IR transforms in preparation for
444 /// instruction selection.
445 void TargetPassConfig::addISelPrepare() {
446   addPreISel();
447
448   // Need to verify DebugInfo *before* creating the stack protector analysis.
449   // It's a function pass, and verifying between it and its users causes a
450   // crash.
451   if (!DisableVerify)
452     addPass(createDebugInfoVerifierPass());
453
454   addPass(createStackProtectorPass(TM));
455
456   if (PrintISelInput)
457     addPass(createPrintFunctionPass(
458         dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
459
460   // All passes which modify the LLVM IR are now complete; run the verifier
461   // to ensure that the IR is valid.
462   if (!DisableVerify)
463     addPass(createVerifierPass());
464 }
465
466 /// Add the complete set of target-independent postISel code generator passes.
467 ///
468 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
469 /// with nontrivial configuration or multiple passes are broken out below in
470 /// add%Stage routines.
471 ///
472 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
473 /// addPre/Post methods with empty header implementations allow injecting
474 /// target-specific fixups just before or after major stages. Additionally,
475 /// targets have the flexibility to change pass order within a stage by
476 /// overriding default implementation of add%Stage routines below. Each
477 /// technique has maintainability tradeoffs because alternate pass orders are
478 /// not well supported. addPre/Post works better if the target pass is easily
479 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
480 /// the target should override the stage instead.
481 ///
482 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
483 /// before/after any target-independent pass. But it's currently overkill.
484 void TargetPassConfig::addMachinePasses() {
485   // Insert a machine instr printer pass after the specified pass.
486   // If -print-machineinstrs specified, print machineinstrs after all passes.
487   if (StringRef(PrintMachineInstrs.getValue()).equals(""))
488     TM->Options.PrintMachineCode = true;
489   else if (!StringRef(PrintMachineInstrs.getValue())
490            .equals("option-unspecified")) {
491     const PassRegistry *PR = PassRegistry::getPassRegistry();
492     const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
493     const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
494     assert (TPI && IPI && "Pass ID not registered!");
495     const char *TID = (const char *)(TPI->getTypeInfo());
496     const char *IID = (const char *)(IPI->getTypeInfo());
497     insertPass(TID, IID);
498   }
499
500   // Print the instruction selected machine code...
501   printAndVerify("After Instruction Selection");
502
503   // Expand pseudo-instructions emitted by ISel.
504   if (addPass(&ExpandISelPseudosID))
505     printAndVerify("After ExpandISelPseudos");
506
507   // Add passes that optimize machine instructions in SSA form.
508   if (getOptLevel() != CodeGenOpt::None) {
509     addMachineSSAOptimization();
510   } else {
511     // If the target requests it, assign local variables to stack slots relative
512     // to one another and simplify frame index references where possible.
513     addPass(&LocalStackSlotAllocationID);
514   }
515
516   // Run pre-ra passes.
517   if (addPreRegAlloc())
518     printAndVerify("After PreRegAlloc passes");
519
520   // Run register allocation and passes that are tightly coupled with it,
521   // including phi elimination and scheduling.
522   if (getOptimizeRegAlloc())
523     addOptimizedRegAlloc(createRegAllocPass(true));
524   else
525     addFastRegAlloc(createRegAllocPass(false));
526
527   // Run post-ra passes.
528   if (addPostRegAlloc())
529     printAndVerify("After PostRegAlloc passes");
530
531   // Insert prolog/epilog code.  Eliminate abstract frame index references...
532   addPass(&PrologEpilogCodeInserterID);
533   printAndVerify("After PrologEpilogCodeInserter");
534
535   /// Add passes that optimize machine instructions after register allocation.
536   if (getOptLevel() != CodeGenOpt::None)
537     addMachineLateOptimization();
538
539   // Expand pseudo instructions before second scheduling pass.
540   addPass(&ExpandPostRAPseudosID);
541   printAndVerify("After ExpandPostRAPseudos");
542
543   // Run pre-sched2 passes.
544   if (addPreSched2())
545     printAndVerify("After PreSched2 passes");
546
547   // Second pass scheduler.
548   if (getOptLevel() != CodeGenOpt::None) {
549     if (MISchedPostRA)
550       addPass(&PostMachineSchedulerID);
551     else
552       addPass(&PostRASchedulerID);
553     printAndVerify("After PostRAScheduler");
554   }
555
556   // GC
557   if (addGCPasses()) {
558     if (PrintGCInfo)
559       addPass(createGCInfoPrinter(dbgs()));
560   }
561
562   // Basic block placement.
563   if (getOptLevel() != CodeGenOpt::None)
564     addBlockPlacement();
565
566   if (addPreEmitPass())
567     printAndVerify("After PreEmit passes");
568
569   addPass(&StackMapLivenessID);
570 }
571
572 /// Add passes that optimize machine instructions in SSA form.
573 void TargetPassConfig::addMachineSSAOptimization() {
574   // Pre-ra tail duplication.
575   if (addPass(&EarlyTailDuplicateID))
576     printAndVerify("After Pre-RegAlloc TailDuplicate");
577
578   // Optimize PHIs before DCE: removing dead PHI cycles may make more
579   // instructions dead.
580   addPass(&OptimizePHIsID);
581
582   // This pass merges large allocas. StackSlotColoring is a different pass
583   // which merges spill slots.
584   addPass(&StackColoringID);
585
586   // If the target requests it, assign local variables to stack slots relative
587   // to one another and simplify frame index references where possible.
588   addPass(&LocalStackSlotAllocationID);
589
590   // With optimization, dead code should already be eliminated. However
591   // there is one known exception: lowered code for arguments that are only
592   // used by tail calls, where the tail calls reuse the incoming stack
593   // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
594   addPass(&DeadMachineInstructionElimID);
595   printAndVerify("After codegen DCE pass");
596
597   // Allow targets to insert passes that improve instruction level parallelism,
598   // like if-conversion. Such passes will typically need dominator trees and
599   // loop info, just like LICM and CSE below.
600   if (addILPOpts())
601     printAndVerify("After ILP optimizations");
602
603   addPass(&MachineLICMID);
604   addPass(&MachineCSEID);
605   addPass(&MachineSinkingID);
606   printAndVerify("After Machine LICM, CSE and Sinking passes");
607
608   addPass(&PeepholeOptimizerID);
609   printAndVerify("After codegen peephole optimization pass");
610 }
611
612 //===---------------------------------------------------------------------===//
613 /// Register Allocation Pass Configuration
614 //===---------------------------------------------------------------------===//
615
616 bool TargetPassConfig::getOptimizeRegAlloc() const {
617   switch (OptimizeRegAlloc) {
618   case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
619   case cl::BOU_TRUE:  return true;
620   case cl::BOU_FALSE: return false;
621   }
622   llvm_unreachable("Invalid optimize-regalloc state");
623 }
624
625 /// RegisterRegAlloc's global Registry tracks allocator registration.
626 MachinePassRegistry RegisterRegAlloc::Registry;
627
628 /// A dummy default pass factory indicates whether the register allocator is
629 /// overridden on the command line.
630 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
631 static RegisterRegAlloc
632 defaultRegAlloc("default",
633                 "pick register allocator based on -O option",
634                 useDefaultRegisterAllocator);
635
636 /// -regalloc=... command line option.
637 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
638                RegisterPassParser<RegisterRegAlloc> >
639 RegAlloc("regalloc",
640          cl::init(&useDefaultRegisterAllocator),
641          cl::desc("Register allocator to use"));
642
643
644 /// Instantiate the default register allocator pass for this target for either
645 /// the optimized or unoptimized allocation path. This will be added to the pass
646 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
647 /// in the optimized case.
648 ///
649 /// A target that uses the standard regalloc pass order for fast or optimized
650 /// allocation may still override this for per-target regalloc
651 /// selection. But -regalloc=... always takes precedence.
652 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
653   if (Optimized)
654     return createGreedyRegisterAllocator();
655   else
656     return createFastRegisterAllocator();
657 }
658
659 /// Find and instantiate the register allocation pass requested by this target
660 /// at the current optimization level.  Different register allocators are
661 /// defined as separate passes because they may require different analysis.
662 ///
663 /// This helper ensures that the regalloc= option is always available,
664 /// even for targets that override the default allocator.
665 ///
666 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
667 /// this can be folded into addPass.
668 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
669   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
670
671   // Initialize the global default.
672   if (!Ctor) {
673     Ctor = RegAlloc;
674     RegisterRegAlloc::setDefault(RegAlloc);
675   }
676   if (Ctor != useDefaultRegisterAllocator)
677     return Ctor();
678
679   // With no -regalloc= override, ask the target for a regalloc pass.
680   return createTargetRegisterAllocator(Optimized);
681 }
682
683 /// Add the minimum set of target-independent passes that are required for
684 /// register allocation. No coalescing or scheduling.
685 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
686   addPass(&PHIEliminationID);
687   addPass(&TwoAddressInstructionPassID);
688
689   addPass(RegAllocPass);
690   printAndVerify("After Register Allocation");
691 }
692
693 /// Add standard target-independent passes that are tightly coupled with
694 /// optimized register allocation, including coalescing, machine instruction
695 /// scheduling, and register allocation itself.
696 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
697   addPass(&ProcessImplicitDefsID);
698
699   // LiveVariables currently requires pure SSA form.
700   //
701   // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
702   // LiveVariables can be removed completely, and LiveIntervals can be directly
703   // computed. (We still either need to regenerate kill flags after regalloc, or
704   // preferably fix the scavenger to not depend on them).
705   addPass(&LiveVariablesID);
706
707   // Edge splitting is smarter with machine loop info.
708   addPass(&MachineLoopInfoID);
709   addPass(&PHIEliminationID);
710
711   // Eventually, we want to run LiveIntervals before PHI elimination.
712   if (EarlyLiveIntervals)
713     addPass(&LiveIntervalsID);
714
715   addPass(&TwoAddressInstructionPassID);
716   addPass(&RegisterCoalescerID);
717
718   // PreRA instruction scheduling.
719   if (addPass(&MachineSchedulerID))
720     printAndVerify("After Machine Scheduling");
721
722   // Add the selected register allocation pass.
723   addPass(RegAllocPass);
724   printAndVerify("After Register Allocation, before rewriter");
725
726   // Allow targets to change the register assignments before rewriting.
727   if (addPreRewrite())
728     printAndVerify("After pre-rewrite passes");
729
730   // Finally rewrite virtual registers.
731   addPass(&VirtRegRewriterID);
732   printAndVerify("After Virtual Register Rewriter");
733
734   // Perform stack slot coloring and post-ra machine LICM.
735   //
736   // FIXME: Re-enable coloring with register when it's capable of adding
737   // kill markers.
738   addPass(&StackSlotColoringID);
739
740   // Run post-ra machine LICM to hoist reloads / remats.
741   //
742   // FIXME: can this move into MachineLateOptimization?
743   addPass(&PostRAMachineLICMID);
744
745   printAndVerify("After StackSlotColoring and postra Machine LICM");
746 }
747
748 //===---------------------------------------------------------------------===//
749 /// Post RegAlloc Pass Configuration
750 //===---------------------------------------------------------------------===//
751
752 /// Add passes that optimize machine instructions after register allocation.
753 void TargetPassConfig::addMachineLateOptimization() {
754   // Branch folding must be run after regalloc and prolog/epilog insertion.
755   if (addPass(&BranchFolderPassID))
756     printAndVerify("After BranchFolding");
757
758   // Tail duplication.
759   // Note that duplicating tail just increases code size and degrades
760   // performance for targets that require Structured Control Flow.
761   // In addition it can also make CFG irreducible. Thus we disable it.
762   if (!TM->requiresStructuredCFG() && addPass(&TailDuplicateID))
763     printAndVerify("After TailDuplicate");
764
765   // Copy propagation.
766   if (addPass(&MachineCopyPropagationID))
767     printAndVerify("After copy propagation pass");
768 }
769
770 /// Add standard GC passes.
771 bool TargetPassConfig::addGCPasses() {
772   addPass(&GCMachineCodeAnalysisID);
773   return true;
774 }
775
776 /// Add standard basic block placement passes.
777 void TargetPassConfig::addBlockPlacement() {
778   if (addPass(&MachineBlockPlacementID)) {
779     // Run a separate pass to collect block placement statistics.
780     if (EnableBlockPlacementStats)
781       addPass(&MachineBlockPlacementStatsID);
782
783     printAndVerify("After machine block placement.");
784   }
785 }