1 //===-- Passes.cpp - Target independent code generation passes ------------===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
13 //===---------------------------------------------------------------------===//
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/Transforms/Scalar.h"
27 #include "llvm/Transforms/Utils/SymbolRewriter.h"
31 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
32 cl::desc("Disable Post Regalloc"));
33 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
34 cl::desc("Disable branch folding"));
35 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
36 cl::desc("Disable tail duplication"));
37 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
38 cl::desc("Disable pre-register allocation tail duplication"));
39 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
40 cl::Hidden, cl::desc("Disable probability-driven block placement"));
41 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
42 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
43 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
44 cl::desc("Disable Stack Slot Coloring"));
45 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
46 cl::desc("Disable Machine Dead Code Elimination"));
47 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
48 cl::desc("Disable Early If-conversion"));
49 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
50 cl::desc("Disable Machine LICM"));
51 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
52 cl::desc("Disable Machine Common Subexpression Elimination"));
53 static cl::opt<cl::boolOrDefault>
54 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
55 cl::desc("Enable optimized register allocation compilation path."));
56 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
58 cl::desc("Disable Machine LICM"));
59 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
60 cl::desc("Disable Machine Sinking"));
61 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
62 cl::desc("Disable Loop Strength Reduction Pass"));
63 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
64 cl::Hidden, cl::desc("Disable ConstantHoisting"));
65 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
66 cl::desc("Disable Codegen Prepare"));
67 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
68 cl::desc("Disable Copy Propagation pass"));
69 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
70 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
71 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
72 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
73 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
74 cl::desc("Print LLVM IR input to isel pass"));
75 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
76 cl::desc("Dump garbage collector data"));
77 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
78 cl::desc("Verify generated machine code"),
82 static cl::opt<std::string>
83 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
84 cl::desc("Print machine instrs"),
85 cl::value_desc("pass-name"), cl::init("option-unspecified"));
87 // Temporary option to allow experimenting with MachineScheduler as a post-RA
88 // scheduler. Targets can "properly" enable this with
89 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
90 // wouldn't be part of the standard pass pipeline, and the target would just add
91 // a PostRA scheduling pass wherever it wants.
92 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
93 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
95 // Experimental option to run live interval analysis early.
96 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
97 cl::desc("Run live interval analysis earlier in the pipeline"));
99 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
100 cl::init(false), cl::Hidden,
101 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
103 /// Allow standard passes to be disabled by command line options. This supports
104 /// simple binary flags that either suppress the pass or do nothing.
105 /// i.e. -disable-mypass=false has no effect.
106 /// These should be converted to boolOrDefault in order to use applyOverride.
107 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
110 return IdentifyingPassPtr();
114 /// Allow standard passes to be disabled by the command line, regardless of who
115 /// is adding the pass.
117 /// StandardID is the pass identified in the standard pass pipeline and provided
118 /// to addPass(). It may be a target-specific ID in the case that the target
119 /// directly adds its own pass, but in that case we harmlessly fall through.
121 /// TargetID is the pass that the target has configured to override StandardID.
123 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
124 /// pass to run. This allows multiple options to control a single pass depending
125 /// on where in the pipeline that pass is added.
126 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
127 IdentifyingPassPtr TargetID) {
128 if (StandardID == &PostRASchedulerID)
129 return applyDisable(TargetID, DisablePostRA);
131 if (StandardID == &BranchFolderPassID)
132 return applyDisable(TargetID, DisableBranchFold);
134 if (StandardID == &TailDuplicateID)
135 return applyDisable(TargetID, DisableTailDuplicate);
137 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
138 return applyDisable(TargetID, DisableEarlyTailDup);
140 if (StandardID == &MachineBlockPlacementID)
141 return applyDisable(TargetID, DisableBlockPlacement);
143 if (StandardID == &StackSlotColoringID)
144 return applyDisable(TargetID, DisableSSC);
146 if (StandardID == &DeadMachineInstructionElimID)
147 return applyDisable(TargetID, DisableMachineDCE);
149 if (StandardID == &EarlyIfConverterID)
150 return applyDisable(TargetID, DisableEarlyIfConversion);
152 if (StandardID == &MachineLICMID)
153 return applyDisable(TargetID, DisableMachineLICM);
155 if (StandardID == &MachineCSEID)
156 return applyDisable(TargetID, DisableMachineCSE);
158 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
159 return applyDisable(TargetID, DisablePostRAMachineLICM);
161 if (StandardID == &MachineSinkingID)
162 return applyDisable(TargetID, DisableMachineSink);
164 if (StandardID == &MachineCopyPropagationID)
165 return applyDisable(TargetID, DisableCopyProp);
170 //===---------------------------------------------------------------------===//
172 //===---------------------------------------------------------------------===//
174 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
175 "Target Pass Configuration", false, false)
176 char TargetPassConfig::ID = 0;
179 char TargetPassConfig::EarlyTailDuplicateID = 0;
180 char TargetPassConfig::PostRAMachineLICMID = 0;
183 class PassConfigImpl {
185 // List of passes explicitly substituted by this target. Normally this is
186 // empty, but it is a convenient way to suppress or replace specific passes
187 // that are part of a standard pass pipeline without overridding the entire
188 // pipeline. This mechanism allows target options to inherit a standard pass's
189 // user interface. For example, a target may disable a standard pass by
190 // default by substituting a pass ID of zero, and the user may still enable
191 // that standard pass with an explicit command line option.
192 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
194 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
195 /// is inserted after each instance of the first one.
196 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
200 // Out of line virtual method.
201 TargetPassConfig::~TargetPassConfig() {
205 // Out of line constructor provides default values for pass options and
206 // registers all common codegen passes.
207 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
208 : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
209 Started(true), Stopped(false), AddingMachinePasses(false), TM(tm),
210 Impl(nullptr), Initialized(false), DisableVerify(false),
211 EnableTailMerge(true) {
213 Impl = new PassConfigImpl();
215 // Register all target independent codegen passes to activate their PassIDs,
216 // including this pass itself.
217 initializeCodeGen(*PassRegistry::getPassRegistry());
219 // Substitute Pseudo Pass IDs for real ones.
220 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
221 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
224 /// Insert InsertedPassID pass after TargetPassID.
225 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
226 IdentifyingPassPtr InsertedPassID) {
227 assert(((!InsertedPassID.isInstance() &&
228 TargetPassID != InsertedPassID.getID()) ||
229 (InsertedPassID.isInstance() &&
230 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
231 "Insert a pass after itself!");
232 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
233 Impl->InsertedPasses.push_back(P);
236 /// createPassConfig - Create a pass configuration object to be used by
237 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
239 /// Targets may override this to extend TargetPassConfig.
240 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
241 return new TargetPassConfig(this, PM);
244 TargetPassConfig::TargetPassConfig()
245 : ImmutablePass(ID), PM(nullptr) {
246 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
249 // Helper to verify the analysis is really immutable.
250 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
251 assert(!Initialized && "PassConfig is immutable");
255 void TargetPassConfig::substitutePass(AnalysisID StandardID,
256 IdentifyingPassPtr TargetID) {
257 Impl->TargetPasses[StandardID] = TargetID;
260 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
261 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
262 I = Impl->TargetPasses.find(ID);
263 if (I == Impl->TargetPasses.end())
268 /// Add a pass to the PassManager if that pass is supposed to be run. If the
269 /// Started/Stopped flags indicate either that the compilation should start at
270 /// a later pass or that it should stop after an earlier pass, then do not add
271 /// the pass. Finally, compare the current pass against the StartAfter
272 /// and StopAfter options and change the Started/Stopped flags accordingly.
273 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
274 assert(!Initialized && "PassConfig is immutable");
276 // Cache the Pass ID here in case the pass manager finds this pass is
277 // redundant with ones already scheduled / available, and deletes it.
278 // Fundamentally, once we add the pass to the manager, we no longer own it
279 // and shouldn't reference it.
280 AnalysisID PassID = P->getPassID();
282 if (Started && !Stopped) {
284 // Construct banner message before PM->add() as that may delete the pass.
285 if (AddingMachinePasses && (printAfter || verifyAfter))
286 Banner = std::string("After ") + std::string(P->getPassName());
288 if (AddingMachinePasses) {
290 addPrintPass(Banner);
292 addVerifyPass(Banner);
297 if (StopAfter == PassID)
299 if (StartAfter == PassID)
301 if (Stopped && !Started)
302 report_fatal_error("Cannot stop compilation after pass that is not run");
305 /// Add a CodeGen pass at this point in the pipeline after checking for target
306 /// and command line overrides.
308 /// addPass cannot return a pointer to the pass instance because is internal the
309 /// PassManager and the instance we create here may already be freed.
310 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
312 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
313 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
314 if (!FinalPtr.isValid())
318 if (FinalPtr.isInstance())
319 P = FinalPtr.getInstance();
321 P = Pass::createPass(FinalPtr.getID());
323 llvm_unreachable("Pass ID not registered");
325 AnalysisID FinalID = P->getPassID();
326 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
328 // Add the passes after the pass P if there is any.
329 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
330 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
332 if ((*I).first == PassID) {
333 assert((*I).second.isValid() && "Illegal Pass ID!");
335 if ((*I).second.isInstance())
336 NP = (*I).second.getInstance();
338 NP = Pass::createPass((*I).second.getID());
339 assert(NP && "Pass ID not registered");
341 addPass(NP, false, false);
347 void TargetPassConfig::printAndVerify(const std::string &Banner) {
348 addPrintPass(Banner);
349 addVerifyPass(Banner);
352 void TargetPassConfig::addPrintPass(const std::string &Banner) {
353 if (TM->shouldPrintMachineCode())
354 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
357 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
358 if (VerifyMachineCode)
359 PM->add(createMachineVerifierPass(Banner));
362 /// Add common target configurable passes that perform LLVM IR to IR transforms
363 /// following machine independent optimization.
364 void TargetPassConfig::addIRPasses() {
365 // Basic AliasAnalysis support.
366 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
367 // BasicAliasAnalysis wins if they disagree. This is intended to help
368 // support "obvious" type-punning idioms.
370 addPass(createCFLAliasAnalysisPass());
371 addPass(createTypeBasedAliasAnalysisPass());
372 addPass(createScopedNoAliasAAPass());
373 addPass(createBasicAliasAnalysisPass());
375 // Before running any passes, run the verifier to determine if the input
376 // coming from the front-end and/or optimizer is valid.
377 if (!DisableVerify) {
378 addPass(createVerifierPass());
379 addPass(createDebugInfoVerifierPass());
382 // Run loop strength reduction before anything else.
383 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
384 addPass(createLoopStrengthReducePass());
386 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
389 // Run GC lowering passes for builtin collectors
390 // TODO: add a pass insertion point here
391 addPass(createGCLoweringPass());
392 addPass(createShadowStackGCLoweringPass());
394 // Make sure that no unreachable blocks are instruction selected.
395 addPass(createUnreachableBlockEliminationPass());
397 // Prepare expensive constants for SelectionDAG.
398 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
399 addPass(createConstantHoistingPass());
401 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
402 addPass(createPartiallyInlineLibCallsPass());
405 /// Turn exception handling constructs into something the code generators can
407 void TargetPassConfig::addPassesToHandleExceptions() {
408 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
409 case ExceptionHandling::SjLj:
410 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
411 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
412 // catch info can get misplaced when a selector ends up more than one block
413 // removed from the parent invoke(s). This could happen when a landing
414 // pad is shared by multiple invokes and is also a target of a normal
415 // edge from elsewhere.
416 addPass(createSjLjEHPreparePass(TM));
418 case ExceptionHandling::DwarfCFI:
419 case ExceptionHandling::ARM:
420 addPass(createDwarfEHPass(TM));
422 case ExceptionHandling::WinEH:
423 // We support using both GCC-style and MSVC-style exceptions on Windows, so
424 // add both preparation passes. Each pass will only actually run if it
425 // recognizes the personality function.
426 addPass(createWinEHPass(TM));
427 addPass(createDwarfEHPass(TM));
429 case ExceptionHandling::None:
430 addPass(createLowerInvokePass());
432 // The lower invoke pass may create unreachable code. Remove it.
433 addPass(createUnreachableBlockEliminationPass());
438 /// Add pass to prepare the LLVM IR for code generation. This should be done
439 /// before exception handling preparation passes.
440 void TargetPassConfig::addCodeGenPrepare() {
441 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
442 addPass(createCodeGenPreparePass(TM));
443 addPass(createRewriteSymbolsPass());
446 /// Add common passes that perform LLVM IR to IR transforms in preparation for
447 /// instruction selection.
448 void TargetPassConfig::addISelPrepare() {
451 // Need to verify DebugInfo *before* creating the stack protector analysis.
452 // It's a function pass, and verifying between it and its users causes a
455 addPass(createDebugInfoVerifierPass());
457 addPass(createStackProtectorPass(TM));
460 addPass(createPrintFunctionPass(
461 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
463 // All passes which modify the LLVM IR are now complete; run the verifier
464 // to ensure that the IR is valid.
466 addPass(createVerifierPass());
469 /// Add the complete set of target-independent postISel code generator passes.
471 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
472 /// with nontrivial configuration or multiple passes are broken out below in
473 /// add%Stage routines.
475 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
476 /// addPre/Post methods with empty header implementations allow injecting
477 /// target-specific fixups just before or after major stages. Additionally,
478 /// targets have the flexibility to change pass order within a stage by
479 /// overriding default implementation of add%Stage routines below. Each
480 /// technique has maintainability tradeoffs because alternate pass orders are
481 /// not well supported. addPre/Post works better if the target pass is easily
482 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
483 /// the target should override the stage instead.
485 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
486 /// before/after any target-independent pass. But it's currently overkill.
487 void TargetPassConfig::addMachinePasses() {
488 AddingMachinePasses = true;
490 // Insert a machine instr printer pass after the specified pass.
491 // If -print-machineinstrs specified, print machineinstrs after all passes.
492 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
493 TM->Options.PrintMachineCode = true;
494 else if (!StringRef(PrintMachineInstrs.getValue())
495 .equals("option-unspecified")) {
496 const PassRegistry *PR = PassRegistry::getPassRegistry();
497 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
498 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
499 assert (TPI && IPI && "Pass ID not registered!");
500 const char *TID = (const char *)(TPI->getTypeInfo());
501 const char *IID = (const char *)(IPI->getTypeInfo());
502 insertPass(TID, IID);
505 // Print the instruction selected machine code...
506 printAndVerify("After Instruction Selection");
508 // Expand pseudo-instructions emitted by ISel.
509 addPass(&ExpandISelPseudosID);
511 // Add passes that optimize machine instructions in SSA form.
512 if (getOptLevel() != CodeGenOpt::None) {
513 addMachineSSAOptimization();
515 // If the target requests it, assign local variables to stack slots relative
516 // to one another and simplify frame index references where possible.
517 addPass(&LocalStackSlotAllocationID, false);
520 // Run pre-ra passes.
523 // Run register allocation and passes that are tightly coupled with it,
524 // including phi elimination and scheduling.
525 if (getOptimizeRegAlloc())
526 addOptimizedRegAlloc(createRegAllocPass(true));
528 addFastRegAlloc(createRegAllocPass(false));
530 // Run post-ra passes.
533 // Insert prolog/epilog code. Eliminate abstract frame index references...
534 addPass(&PrologEpilogCodeInserterID);
536 /// Add passes that optimize machine instructions after register allocation.
537 if (getOptLevel() != CodeGenOpt::None)
538 addMachineLateOptimization();
540 // Expand pseudo instructions before second scheduling pass.
541 addPass(&ExpandPostRAPseudosID);
543 // Run pre-sched2 passes.
546 // Second pass scheduler.
547 if (getOptLevel() != CodeGenOpt::None) {
549 addPass(&PostMachineSchedulerID);
551 addPass(&PostRASchedulerID);
557 addPass(createGCInfoPrinter(dbgs()), false, false);
560 // Basic block placement.
561 if (getOptLevel() != CodeGenOpt::None)
566 addPass(&StackMapLivenessID, false);
568 AddingMachinePasses = false;
571 /// Add passes that optimize machine instructions in SSA form.
572 void TargetPassConfig::addMachineSSAOptimization() {
573 // Pre-ra tail duplication.
574 addPass(&EarlyTailDuplicateID);
576 // Optimize PHIs before DCE: removing dead PHI cycles may make more
577 // instructions dead.
578 addPass(&OptimizePHIsID, false);
580 // This pass merges large allocas. StackSlotColoring is a different pass
581 // which merges spill slots.
582 addPass(&StackColoringID, false);
584 // If the target requests it, assign local variables to stack slots relative
585 // to one another and simplify frame index references where possible.
586 addPass(&LocalStackSlotAllocationID, false);
588 // With optimization, dead code should already be eliminated. However
589 // there is one known exception: lowered code for arguments that are only
590 // used by tail calls, where the tail calls reuse the incoming stack
591 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
592 addPass(&DeadMachineInstructionElimID);
594 // Allow targets to insert passes that improve instruction level parallelism,
595 // like if-conversion. Such passes will typically need dominator trees and
596 // loop info, just like LICM and CSE below.
599 addPass(&MachineLICMID, false);
600 addPass(&MachineCSEID, false);
601 addPass(&MachineSinkingID);
603 addPass(&PeepholeOptimizerID, false);
604 // Clean-up the dead code that may have been generated by peephole
606 addPass(&DeadMachineInstructionElimID);
609 //===---------------------------------------------------------------------===//
610 /// Register Allocation Pass Configuration
611 //===---------------------------------------------------------------------===//
613 bool TargetPassConfig::getOptimizeRegAlloc() const {
614 switch (OptimizeRegAlloc) {
615 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
616 case cl::BOU_TRUE: return true;
617 case cl::BOU_FALSE: return false;
619 llvm_unreachable("Invalid optimize-regalloc state");
622 /// RegisterRegAlloc's global Registry tracks allocator registration.
623 MachinePassRegistry RegisterRegAlloc::Registry;
625 /// A dummy default pass factory indicates whether the register allocator is
626 /// overridden on the command line.
627 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
628 static RegisterRegAlloc
629 defaultRegAlloc("default",
630 "pick register allocator based on -O option",
631 useDefaultRegisterAllocator);
633 /// -regalloc=... command line option.
634 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
635 RegisterPassParser<RegisterRegAlloc> >
637 cl::init(&useDefaultRegisterAllocator),
638 cl::desc("Register allocator to use"));
641 /// Instantiate the default register allocator pass for this target for either
642 /// the optimized or unoptimized allocation path. This will be added to the pass
643 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
644 /// in the optimized case.
646 /// A target that uses the standard regalloc pass order for fast or optimized
647 /// allocation may still override this for per-target regalloc
648 /// selection. But -regalloc=... always takes precedence.
649 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
651 return createGreedyRegisterAllocator();
653 return createFastRegisterAllocator();
656 /// Find and instantiate the register allocation pass requested by this target
657 /// at the current optimization level. Different register allocators are
658 /// defined as separate passes because they may require different analysis.
660 /// This helper ensures that the regalloc= option is always available,
661 /// even for targets that override the default allocator.
663 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
664 /// this can be folded into addPass.
665 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
666 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
668 // Initialize the global default.
671 RegisterRegAlloc::setDefault(RegAlloc);
673 if (Ctor != useDefaultRegisterAllocator)
676 // With no -regalloc= override, ask the target for a regalloc pass.
677 return createTargetRegisterAllocator(Optimized);
680 /// Return true if the default global register allocator is in use and
681 /// has not be overriden on the command line with '-regalloc=...'
682 bool TargetPassConfig::usingDefaultRegAlloc() const {
683 return RegAlloc.getNumOccurrences() == 0;
686 /// Add the minimum set of target-independent passes that are required for
687 /// register allocation. No coalescing or scheduling.
688 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
689 addPass(&PHIEliminationID, false);
690 addPass(&TwoAddressInstructionPassID, false);
692 addPass(RegAllocPass);
695 /// Add standard target-independent passes that are tightly coupled with
696 /// optimized register allocation, including coalescing, machine instruction
697 /// scheduling, and register allocation itself.
698 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
699 addPass(&ProcessImplicitDefsID, false);
701 // LiveVariables currently requires pure SSA form.
703 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
704 // LiveVariables can be removed completely, and LiveIntervals can be directly
705 // computed. (We still either need to regenerate kill flags after regalloc, or
706 // preferably fix the scavenger to not depend on them).
707 addPass(&LiveVariablesID, false);
709 // Edge splitting is smarter with machine loop info.
710 addPass(&MachineLoopInfoID, false);
711 addPass(&PHIEliminationID, false);
713 // Eventually, we want to run LiveIntervals before PHI elimination.
714 if (EarlyLiveIntervals)
715 addPass(&LiveIntervalsID, false);
717 addPass(&TwoAddressInstructionPassID, false);
718 addPass(&RegisterCoalescerID);
720 // PreRA instruction scheduling.
721 addPass(&MachineSchedulerID);
723 // Add the selected register allocation pass.
724 addPass(RegAllocPass);
726 // Allow targets to change the register assignments before rewriting.
729 // Finally rewrite virtual registers.
730 addPass(&VirtRegRewriterID);
732 // Perform stack slot coloring and post-ra machine LICM.
734 // FIXME: Re-enable coloring with register when it's capable of adding
736 addPass(&StackSlotColoringID);
738 // Run post-ra machine LICM to hoist reloads / remats.
740 // FIXME: can this move into MachineLateOptimization?
741 addPass(&PostRAMachineLICMID);
744 //===---------------------------------------------------------------------===//
745 /// Post RegAlloc Pass Configuration
746 //===---------------------------------------------------------------------===//
748 /// Add passes that optimize machine instructions after register allocation.
749 void TargetPassConfig::addMachineLateOptimization() {
750 // Branch folding must be run after regalloc and prolog/epilog insertion.
751 addPass(&BranchFolderPassID);
754 // Note that duplicating tail just increases code size and degrades
755 // performance for targets that require Structured Control Flow.
756 // In addition it can also make CFG irreducible. Thus we disable it.
757 if (!TM->requiresStructuredCFG())
758 addPass(&TailDuplicateID);
761 addPass(&MachineCopyPropagationID);
764 /// Add standard GC passes.
765 bool TargetPassConfig::addGCPasses() {
766 addPass(&GCMachineCodeAnalysisID, false);
770 /// Add standard basic block placement passes.
771 void TargetPassConfig::addBlockPlacement() {
772 if (addPass(&MachineBlockPlacementID, false)) {
773 // Run a separate pass to collect block placement statistics.
774 if (EnableBlockPlacementStats)
775 addPass(&MachineBlockPlacementStatsID);