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/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/GCStrategy.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/RegAllocRegistry.h"
22 #include "llvm/MC/MCAsmInfo.h"
23 #include "llvm/PassManager.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Target/TargetLowering.h"
28 #include "llvm/Target/TargetSubtargetInfo.h"
29 #include "llvm/Transforms/Scalar.h"
34 extern cl::opt<bool> EnableStackMapLiveness;
35 extern cl::opt<bool> EnablePatchPointLiveness;
38 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
39 cl::desc("Disable Post Regalloc"));
40 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
41 cl::desc("Disable branch folding"));
42 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
43 cl::desc("Disable tail duplication"));
44 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
45 cl::desc("Disable pre-register allocation tail duplication"));
46 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
47 cl::Hidden, cl::desc("Disable probability-driven block placement"));
48 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
49 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
50 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
51 cl::desc("Disable Stack Slot Coloring"));
52 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
53 cl::desc("Disable Machine Dead Code Elimination"));
54 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
55 cl::desc("Disable Early If-conversion"));
56 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
57 cl::desc("Disable Machine LICM"));
58 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
59 cl::desc("Disable Machine Common Subexpression Elimination"));
60 static cl::opt<cl::boolOrDefault>
61 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
62 cl::desc("Enable optimized register allocation compilation path."));
63 static cl::opt<cl::boolOrDefault>
64 EnableMachineSched("enable-misched", cl::Hidden,
65 cl::desc("Enable the machine instruction scheduling pass."));
66 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
68 cl::desc("Disable Machine LICM"));
69 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
70 cl::desc("Disable Machine Sinking"));
71 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
72 cl::desc("Disable Loop Strength Reduction Pass"));
73 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
74 cl::desc("Disable Codegen Prepare"));
75 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
76 cl::desc("Disable Copy Propagation pass"));
77 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
78 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
79 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
80 cl::desc("Print LLVM IR input to isel pass"));
81 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
82 cl::desc("Dump garbage collector data"));
83 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
84 cl::desc("Verify generated machine code"),
85 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
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"));
91 // Temporary option to allow experimenting with MachineScheduler as a post-RA
92 // scheduler. Targets can "properly" enable this with
93 // substitutePass(&PostRASchedulerID, &MachineSchedulerID); Ideally it wouldn't
94 // be part of the standard pass pipeline, and the target would just add a PostRA
95 // 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)"));
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"));
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 Pass selection to be overriden by command line options. This supports
115 /// flags with ternary conditions. TargetID is passed through by default. The
116 /// pass is suppressed when the option is false. When the option is true, the
117 /// StandardID is selected if the target provides no default.
118 static IdentifyingPassPtr applyOverride(IdentifyingPassPtr TargetID,
119 cl::boolOrDefault Override,
120 AnalysisID StandardID) {
125 if (TargetID.isValid())
128 report_fatal_error("Target cannot enable pass");
131 return IdentifyingPassPtr();
133 llvm_unreachable("Invalid command line option state");
136 /// Allow standard passes to be disabled by the command line, regardless of who
137 /// is adding the pass.
139 /// StandardID is the pass identified in the standard pass pipeline and provided
140 /// to addPass(). It may be a target-specific ID in the case that the target
141 /// directly adds its own pass, but in that case we harmlessly fall through.
143 /// TargetID is the pass that the target has configured to override StandardID.
145 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
146 /// pass to run. This allows multiple options to control a single pass depending
147 /// on where in the pipeline that pass is added.
148 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
149 IdentifyingPassPtr TargetID) {
150 if (StandardID == &PostRASchedulerID)
151 return applyDisable(TargetID, DisablePostRA);
153 if (StandardID == &BranchFolderPassID)
154 return applyDisable(TargetID, DisableBranchFold);
156 if (StandardID == &TailDuplicateID)
157 return applyDisable(TargetID, DisableTailDuplicate);
159 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
160 return applyDisable(TargetID, DisableEarlyTailDup);
162 if (StandardID == &MachineBlockPlacementID)
163 return applyDisable(TargetID, DisableBlockPlacement);
165 if (StandardID == &StackSlotColoringID)
166 return applyDisable(TargetID, DisableSSC);
168 if (StandardID == &DeadMachineInstructionElimID)
169 return applyDisable(TargetID, DisableMachineDCE);
171 if (StandardID == &EarlyIfConverterID)
172 return applyDisable(TargetID, DisableEarlyIfConversion);
174 if (StandardID == &MachineLICMID)
175 return applyDisable(TargetID, DisableMachineLICM);
177 if (StandardID == &MachineCSEID)
178 return applyDisable(TargetID, DisableMachineCSE);
180 if (StandardID == &MachineSchedulerID)
181 return applyOverride(TargetID, EnableMachineSched, StandardID);
183 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
184 return applyDisable(TargetID, DisablePostRAMachineLICM);
186 if (StandardID == &MachineSinkingID)
187 return applyDisable(TargetID, DisableMachineSink);
189 if (StandardID == &MachineCopyPropagationID)
190 return applyDisable(TargetID, DisableCopyProp);
195 //===---------------------------------------------------------------------===//
197 //===---------------------------------------------------------------------===//
199 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
200 "Target Pass Configuration", false, false)
201 char TargetPassConfig::ID = 0;
204 char TargetPassConfig::EarlyTailDuplicateID = 0;
205 char TargetPassConfig::PostRAMachineLICMID = 0;
208 class PassConfigImpl {
210 // List of passes explicitly substituted by this target. Normally this is
211 // empty, but it is a convenient way to suppress or replace specific passes
212 // that are part of a standard pass pipeline without overridding the entire
213 // pipeline. This mechanism allows target options to inherit a standard pass's
214 // user interface. For example, a target may disable a standard pass by
215 // default by substituting a pass ID of zero, and the user may still enable
216 // that standard pass with an explicit command line option.
217 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
219 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
220 /// is inserted after each instance of the first one.
221 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
225 // Out of line virtual method.
226 TargetPassConfig::~TargetPassConfig() {
230 // Out of line constructor provides default values for pass options and
231 // registers all common codegen passes.
232 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
233 : ImmutablePass(ID), PM(&pm), StartAfter(0), StopAfter(0),
234 Started(true), Stopped(false), TM(tm), Impl(0), Initialized(false),
235 DisableVerify(false),
236 EnableTailMerge(true) {
238 Impl = new PassConfigImpl();
240 // Register all target independent codegen passes to activate their PassIDs,
241 // including this pass itself.
242 initializeCodeGen(*PassRegistry::getPassRegistry());
244 // Substitute Pseudo Pass IDs for real ones.
245 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
246 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
248 // Temporarily disable experimental passes.
249 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
250 if (!ST.useMachineScheduler())
251 disablePass(&MachineSchedulerID);
254 /// Insert InsertedPassID pass after TargetPassID.
255 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
256 IdentifyingPassPtr InsertedPassID) {
257 assert(((!InsertedPassID.isInstance() &&
258 TargetPassID != InsertedPassID.getID()) ||
259 (InsertedPassID.isInstance() &&
260 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
261 "Insert a pass after itself!");
262 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
263 Impl->InsertedPasses.push_back(P);
266 /// createPassConfig - Create a pass configuration object to be used by
267 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
269 /// Targets may override this to extend TargetPassConfig.
270 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
271 return new TargetPassConfig(this, PM);
274 TargetPassConfig::TargetPassConfig()
275 : ImmutablePass(ID), PM(0) {
276 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
279 // Helper to verify the analysis is really immutable.
280 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
281 assert(!Initialized && "PassConfig is immutable");
285 void TargetPassConfig::substitutePass(AnalysisID StandardID,
286 IdentifyingPassPtr TargetID) {
287 Impl->TargetPasses[StandardID] = TargetID;
290 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
291 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
292 I = Impl->TargetPasses.find(ID);
293 if (I == Impl->TargetPasses.end())
298 /// Add a pass to the PassManager if that pass is supposed to be run. If the
299 /// Started/Stopped flags indicate either that the compilation should start at
300 /// a later pass or that it should stop after an earlier pass, then do not add
301 /// the pass. Finally, compare the current pass against the StartAfter
302 /// and StopAfter options and change the Started/Stopped flags accordingly.
303 void TargetPassConfig::addPass(Pass *P) {
304 assert(!Initialized && "PassConfig is immutable");
306 // Cache the Pass ID here in case the pass manager finds this pass is
307 // redundant with ones already scheduled / available, and deletes it.
308 // Fundamentally, once we add the pass to the manager, we no longer own it
309 // and shouldn't reference it.
310 AnalysisID PassID = P->getPassID();
312 if (Started && !Stopped)
316 if (StopAfter == PassID)
318 if (StartAfter == PassID)
320 if (Stopped && !Started)
321 report_fatal_error("Cannot stop compilation after pass that is not run");
324 /// Add a CodeGen pass at this point in the pipeline after checking for target
325 /// and command line overrides.
327 /// addPass cannot return a pointer to the pass instance because is internal the
328 /// PassManager and the instance we create here may already be freed.
329 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
330 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
331 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
332 if (!FinalPtr.isValid())
336 if (FinalPtr.isInstance())
337 P = FinalPtr.getInstance();
339 P = Pass::createPass(FinalPtr.getID());
341 llvm_unreachable("Pass ID not registered");
343 AnalysisID FinalID = P->getPassID();
344 addPass(P); // Ends the lifetime of P.
346 // Add the passes after the pass P if there is any.
347 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
348 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
350 if ((*I).first == PassID) {
351 assert((*I).second.isValid() && "Illegal Pass ID!");
353 if ((*I).second.isInstance())
354 NP = (*I).second.getInstance();
356 NP = Pass::createPass((*I).second.getID());
357 assert(NP && "Pass ID not registered");
365 void TargetPassConfig::printAndVerify(const char *Banner) {
366 if (TM->shouldPrintMachineCode())
367 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
369 if (VerifyMachineCode)
370 addPass(createMachineVerifierPass(Banner));
373 /// Add common target configurable passes that perform LLVM IR to IR transforms
374 /// following machine independent optimization.
375 void TargetPassConfig::addIRPasses() {
376 // Basic AliasAnalysis support.
377 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
378 // BasicAliasAnalysis wins if they disagree. This is intended to help
379 // support "obvious" type-punning idioms.
380 addPass(createTypeBasedAliasAnalysisPass());
381 addPass(createBasicAliasAnalysisPass());
383 // Before running any passes, run the verifier to determine if the input
384 // coming from the front-end and/or optimizer is valid.
386 addPass(createVerifierPass());
388 // Run loop strength reduction before anything else.
389 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
390 addPass(createLoopStrengthReducePass());
392 addPass(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
395 addPass(createGCLoweringPass());
397 // Make sure that no unreachable blocks are instruction selected.
398 addPass(createUnreachableBlockEliminationPass());
401 /// Turn exception handling constructs into something the code generators can
403 void TargetPassConfig::addPassesToHandleExceptions() {
404 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
405 case ExceptionHandling::SjLj:
406 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
407 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
408 // catch info can get misplaced when a selector ends up more than one block
409 // removed from the parent invoke(s). This could happen when a landing
410 // pad is shared by multiple invokes and is also a target of a normal
411 // edge from elsewhere.
412 addPass(createSjLjEHPreparePass(TM));
414 case ExceptionHandling::DwarfCFI:
415 case ExceptionHandling::ARM:
416 case ExceptionHandling::Win64:
417 addPass(createDwarfEHPass(TM));
419 case ExceptionHandling::None:
420 addPass(createLowerInvokePass(TM));
422 // The lower invoke pass may create unreachable code. Remove it.
423 addPass(createUnreachableBlockEliminationPass());
428 /// Add pass to prepare the LLVM IR for code generation. This should be done
429 /// before exception handling preparation passes.
430 void TargetPassConfig::addCodeGenPrepare() {
431 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
432 addPass(createCodeGenPreparePass(TM));
435 /// Add common passes that perform LLVM IR to IR transforms in preparation for
436 /// instruction selection.
437 void TargetPassConfig::addISelPrepare() {
440 addPass(createStackProtectorPass(TM));
443 addPass(createPrintFunctionPass("\n\n"
444 "*** Final LLVM Code input to ISel ***\n",
447 // All passes which modify the LLVM IR are now complete; run the verifier
448 // to ensure that the IR is valid.
450 addPass(createVerifierPass());
453 /// Add the complete set of target-independent postISel code generator passes.
455 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
456 /// with nontrivial configuration or multiple passes are broken out below in
457 /// add%Stage routines.
459 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
460 /// addPre/Post methods with empty header implementations allow injecting
461 /// target-specific fixups just before or after major stages. Additionally,
462 /// targets have the flexibility to change pass order within a stage by
463 /// overriding default implementation of add%Stage routines below. Each
464 /// technique has maintainability tradeoffs because alternate pass orders are
465 /// not well supported. addPre/Post works better if the target pass is easily
466 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
467 /// the target should override the stage instead.
469 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
470 /// before/after any target-independent pass. But it's currently overkill.
471 void TargetPassConfig::addMachinePasses() {
472 // Insert a machine instr printer pass after the specified pass.
473 // If -print-machineinstrs specified, print machineinstrs after all passes.
474 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
475 TM->Options.PrintMachineCode = true;
476 else if (!StringRef(PrintMachineInstrs.getValue())
477 .equals("option-unspecified")) {
478 const PassRegistry *PR = PassRegistry::getPassRegistry();
479 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
480 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
481 assert (TPI && IPI && "Pass ID not registered!");
482 const char *TID = (const char *)(TPI->getTypeInfo());
483 const char *IID = (const char *)(IPI->getTypeInfo());
484 insertPass(TID, IID);
487 // Print the instruction selected machine code...
488 printAndVerify("After Instruction Selection");
490 // Expand pseudo-instructions emitted by ISel.
491 if (addPass(&ExpandISelPseudosID))
492 printAndVerify("After ExpandISelPseudos");
494 // Add passes that optimize machine instructions in SSA form.
495 if (getOptLevel() != CodeGenOpt::None) {
496 addMachineSSAOptimization();
498 // If the target requests it, assign local variables to stack slots relative
499 // to one another and simplify frame index references where possible.
500 addPass(&LocalStackSlotAllocationID);
503 // Run pre-ra passes.
504 if (addPreRegAlloc())
505 printAndVerify("After PreRegAlloc passes");
507 // Run register allocation and passes that are tightly coupled with it,
508 // including phi elimination and scheduling.
509 if (getOptimizeRegAlloc())
510 addOptimizedRegAlloc(createRegAllocPass(true));
512 addFastRegAlloc(createRegAllocPass(false));
514 // Run post-ra passes.
515 if (addPostRegAlloc())
516 printAndVerify("After PostRegAlloc passes");
518 // Insert prolog/epilog code. Eliminate abstract frame index references...
519 addPass(&PrologEpilogCodeInserterID);
520 printAndVerify("After PrologEpilogCodeInserter");
522 /// Add passes that optimize machine instructions after register allocation.
523 if (getOptLevel() != CodeGenOpt::None)
524 addMachineLateOptimization();
526 // Expand pseudo instructions before second scheduling pass.
527 addPass(&ExpandPostRAPseudosID);
528 printAndVerify("After ExpandPostRAPseudos");
530 // Run pre-sched2 passes.
532 printAndVerify("After PreSched2 passes");
534 // Second pass scheduler.
535 if (getOptLevel() != CodeGenOpt::None) {
537 addPass(&PostMachineSchedulerID);
539 addPass(&PostRASchedulerID);
540 printAndVerify("After PostRAScheduler");
546 addPass(createGCInfoPrinter(dbgs()));
549 // Basic block placement.
550 if (getOptLevel() != CodeGenOpt::None)
553 if (addPreEmitPass())
554 printAndVerify("After PreEmit passes");
556 if (EnableStackMapLiveness || EnablePatchPointLiveness)
557 addPass(&StackMapLivenessID);
560 /// Add passes that optimize machine instructions in SSA form.
561 void TargetPassConfig::addMachineSSAOptimization() {
562 // Pre-ra tail duplication.
563 if (addPass(&EarlyTailDuplicateID))
564 printAndVerify("After Pre-RegAlloc TailDuplicate");
566 // Optimize PHIs before DCE: removing dead PHI cycles may make more
567 // instructions dead.
568 addPass(&OptimizePHIsID);
570 // This pass merges large allocas. StackSlotColoring is a different pass
571 // which merges spill slots.
572 addPass(&StackColoringID);
574 // If the target requests it, assign local variables to stack slots relative
575 // to one another and simplify frame index references where possible.
576 addPass(&LocalStackSlotAllocationID);
578 // With optimization, dead code should already be eliminated. However
579 // there is one known exception: lowered code for arguments that are only
580 // used by tail calls, where the tail calls reuse the incoming stack
581 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
582 addPass(&DeadMachineInstructionElimID);
583 printAndVerify("After codegen DCE pass");
585 // Allow targets to insert passes that improve instruction level parallelism,
586 // like if-conversion. Such passes will typically need dominator trees and
587 // loop info, just like LICM and CSE below.
589 printAndVerify("After ILP optimizations");
591 addPass(&MachineLICMID);
592 addPass(&MachineCSEID);
593 addPass(&MachineSinkingID);
594 printAndVerify("After Machine LICM, CSE and Sinking passes");
596 addPass(&PeepholeOptimizerID);
597 printAndVerify("After codegen peephole optimization pass");
600 //===---------------------------------------------------------------------===//
601 /// Register Allocation Pass Configuration
602 //===---------------------------------------------------------------------===//
604 bool TargetPassConfig::getOptimizeRegAlloc() const {
605 switch (OptimizeRegAlloc) {
606 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
607 case cl::BOU_TRUE: return true;
608 case cl::BOU_FALSE: return false;
610 llvm_unreachable("Invalid optimize-regalloc state");
613 /// RegisterRegAlloc's global Registry tracks allocator registration.
614 MachinePassRegistry RegisterRegAlloc::Registry;
616 /// A dummy default pass factory indicates whether the register allocator is
617 /// overridden on the command line.
618 static FunctionPass *useDefaultRegisterAllocator() { return 0; }
619 static RegisterRegAlloc
620 defaultRegAlloc("default",
621 "pick register allocator based on -O option",
622 useDefaultRegisterAllocator);
624 /// -regalloc=... command line option.
625 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
626 RegisterPassParser<RegisterRegAlloc> >
628 cl::init(&useDefaultRegisterAllocator),
629 cl::desc("Register allocator to use"));
632 /// Instantiate the default register allocator pass for this target for either
633 /// the optimized or unoptimized allocation path. This will be added to the pass
634 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
635 /// in the optimized case.
637 /// A target that uses the standard regalloc pass order for fast or optimized
638 /// allocation may still override this for per-target regalloc
639 /// selection. But -regalloc=... always takes precedence.
640 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
642 return createGreedyRegisterAllocator();
644 return createFastRegisterAllocator();
647 /// Find and instantiate the register allocation pass requested by this target
648 /// at the current optimization level. Different register allocators are
649 /// defined as separate passes because they may require different analysis.
651 /// This helper ensures that the regalloc= option is always available,
652 /// even for targets that override the default allocator.
654 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
655 /// this can be folded into addPass.
656 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
657 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
659 // Initialize the global default.
662 RegisterRegAlloc::setDefault(RegAlloc);
664 if (Ctor != useDefaultRegisterAllocator)
667 // With no -regalloc= override, ask the target for a regalloc pass.
668 return createTargetRegisterAllocator(Optimized);
671 /// Add the minimum set of target-independent passes that are required for
672 /// register allocation. No coalescing or scheduling.
673 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
674 addPass(&PHIEliminationID);
675 addPass(&TwoAddressInstructionPassID);
677 addPass(RegAllocPass);
678 printAndVerify("After Register Allocation");
681 /// Add standard target-independent passes that are tightly coupled with
682 /// optimized register allocation, including coalescing, machine instruction
683 /// scheduling, and register allocation itself.
684 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
685 addPass(&ProcessImplicitDefsID);
687 // LiveVariables currently requires pure SSA form.
689 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
690 // LiveVariables can be removed completely, and LiveIntervals can be directly
691 // computed. (We still either need to regenerate kill flags after regalloc, or
692 // preferably fix the scavenger to not depend on them).
693 addPass(&LiveVariablesID);
695 // Edge splitting is smarter with machine loop info.
696 addPass(&MachineLoopInfoID);
697 addPass(&PHIEliminationID);
699 // Eventually, we want to run LiveIntervals before PHI elimination.
700 if (EarlyLiveIntervals)
701 addPass(&LiveIntervalsID);
703 addPass(&TwoAddressInstructionPassID);
704 addPass(&RegisterCoalescerID);
706 // PreRA instruction scheduling.
707 if (addPass(&MachineSchedulerID))
708 printAndVerify("After Machine Scheduling");
710 // Add the selected register allocation pass.
711 addPass(RegAllocPass);
712 printAndVerify("After Register Allocation, before rewriter");
714 // Allow targets to change the register assignments before rewriting.
716 printAndVerify("After pre-rewrite passes");
718 // Finally rewrite virtual registers.
719 addPass(&VirtRegRewriterID);
720 printAndVerify("After Virtual Register Rewriter");
722 // Perform stack slot coloring and post-ra machine LICM.
724 // FIXME: Re-enable coloring with register when it's capable of adding
726 addPass(&StackSlotColoringID);
728 // Run post-ra machine LICM to hoist reloads / remats.
730 // FIXME: can this move into MachineLateOptimization?
731 addPass(&PostRAMachineLICMID);
733 printAndVerify("After StackSlotColoring and postra Machine LICM");
736 //===---------------------------------------------------------------------===//
737 /// Post RegAlloc Pass Configuration
738 //===---------------------------------------------------------------------===//
740 /// Add passes that optimize machine instructions after register allocation.
741 void TargetPassConfig::addMachineLateOptimization() {
742 // Branch folding must be run after regalloc and prolog/epilog insertion.
743 if (addPass(&BranchFolderPassID))
744 printAndVerify("After BranchFolding");
747 // Note that duplicating tail just increases code size and degrades
748 // performance for targets that require Structured Control Flow.
749 // In addition it can also make CFG irreducible. Thus we disable it.
750 if (!TM->requiresStructuredCFG() && addPass(&TailDuplicateID))
751 printAndVerify("After TailDuplicate");
754 if (addPass(&MachineCopyPropagationID))
755 printAndVerify("After copy propagation pass");
758 /// Add standard GC passes.
759 bool TargetPassConfig::addGCPasses() {
760 addPass(&GCMachineCodeAnalysisID);
764 /// Add standard basic block placement passes.
765 void TargetPassConfig::addBlockPlacement() {
766 if (addPass(&MachineBlockPlacementID)) {
767 // Run a separate pass to collect block placement statistics.
768 if (EnableBlockPlacementStats)
769 addPass(&MachineBlockPlacementStatsID);
771 printAndVerify("After machine block placement.");