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