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