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