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