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/BasicAliasAnalysis.h"
17 #include "llvm/Analysis/Passes.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/IR/IRPrintingPasses.h"
21 #include "llvm/IR/LegacyPassManager.h"
22 #include "llvm/IR/Verifier.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/Support/CommandLine.h"
25 #include "llvm/Support/Debug.h"
26 #include "llvm/Support/ErrorHandling.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Instrumentation.h"
29 #include "llvm/Transforms/Scalar.h"
30 #include "llvm/Transforms/Utils/SymbolRewriter.h"
34 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
35 cl::desc("Disable Post Regalloc"));
36 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
37 cl::desc("Disable branch folding"));
38 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
39 cl::desc("Disable tail duplication"));
40 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
41 cl::desc("Disable pre-register allocation tail duplication"));
42 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
43 cl::Hidden, cl::desc("Disable probability-driven block placement"));
44 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
45 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
46 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
47 cl::desc("Disable Stack Slot Coloring"));
48 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
49 cl::desc("Disable Machine Dead Code Elimination"));
50 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
51 cl::desc("Disable Early If-conversion"));
52 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
53 cl::desc("Disable Machine LICM"));
54 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
55 cl::desc("Disable Machine Common Subexpression Elimination"));
56 static cl::opt<cl::boolOrDefault>
57 EnableShrinkWrapOpt("enable-shrink-wrap", cl::Hidden,
58 cl::desc("enable the shrink-wrapping pass"));
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",
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"),
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"),
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"));
97 // Temporary option to allow experimenting with MachineScheduler as a post-RA
98 // scheduler. Targets can "properly" enable this with
99 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
100 // wouldn't be part of the standard pass pipeline, and the target would just add
101 // a PostRA scheduling pass wherever it wants.
102 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
103 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
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"));
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"));
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,
120 return IdentifyingPassPtr();
124 /// Allow standard passes to be disabled by the command line, regardless of who
125 /// is adding the pass.
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.
131 /// TargetID is the pass that the target has configured to override StandardID.
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);
141 if (StandardID == &BranchFolderPassID)
142 return applyDisable(TargetID, DisableBranchFold);
144 if (StandardID == &TailDuplicateID)
145 return applyDisable(TargetID, DisableTailDuplicate);
147 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
148 return applyDisable(TargetID, DisableEarlyTailDup);
150 if (StandardID == &MachineBlockPlacementID)
151 return applyDisable(TargetID, DisableBlockPlacement);
153 if (StandardID == &StackSlotColoringID)
154 return applyDisable(TargetID, DisableSSC);
156 if (StandardID == &DeadMachineInstructionElimID)
157 return applyDisable(TargetID, DisableMachineDCE);
159 if (StandardID == &EarlyIfConverterID)
160 return applyDisable(TargetID, DisableEarlyIfConversion);
162 if (StandardID == &MachineLICMID)
163 return applyDisable(TargetID, DisableMachineLICM);
165 if (StandardID == &MachineCSEID)
166 return applyDisable(TargetID, DisableMachineCSE);
168 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
169 return applyDisable(TargetID, DisablePostRAMachineLICM);
171 if (StandardID == &MachineSinkingID)
172 return applyDisable(TargetID, DisableMachineSink);
174 if (StandardID == &MachineCopyPropagationID)
175 return applyDisable(TargetID, DisableCopyProp);
180 //===---------------------------------------------------------------------===//
182 //===---------------------------------------------------------------------===//
184 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
185 "Target Pass Configuration", false, false)
186 char TargetPassConfig::ID = 0;
189 char TargetPassConfig::EarlyTailDuplicateID = 0;
190 char TargetPassConfig::PostRAMachineLICMID = 0;
193 class PassConfigImpl {
195 // List of passes explicitly substituted by this target. Normally this is
196 // empty, but it is a convenient way to suppress or replace specific passes
197 // that are part of a standard pass pipeline without overridding the entire
198 // pipeline. This mechanism allows target options to inherit a standard pass's
199 // user interface. For example, a target may disable a standard pass by
200 // default by substituting a pass ID of zero, and the user may still enable
201 // that standard pass with an explicit command line option.
202 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
204 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
205 /// is inserted after each instance of the first one.
206 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
210 // Out of line virtual method.
211 TargetPassConfig::~TargetPassConfig() {
215 // Out of line constructor provides default values for pass options and
216 // registers all common codegen passes.
217 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
218 : ImmutablePass(ID), PM(&pm), StartBefore(nullptr), StartAfter(nullptr),
219 StopAfter(nullptr), Started(true), Stopped(false),
220 AddingMachinePasses(false), TM(tm), Impl(nullptr), Initialized(false),
221 DisableVerify(false), EnableTailMerge(true), EnableShrinkWrap(false) {
223 Impl = new PassConfigImpl();
225 // Register all target independent codegen passes to activate their PassIDs,
226 // including this pass itself.
227 initializeCodeGen(*PassRegistry::getPassRegistry());
229 // Substitute Pseudo Pass IDs for real ones.
230 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
231 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
234 /// Insert InsertedPassID pass after TargetPassID.
235 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
236 IdentifyingPassPtr InsertedPassID) {
237 assert(((!InsertedPassID.isInstance() &&
238 TargetPassID != InsertedPassID.getID()) ||
239 (InsertedPassID.isInstance() &&
240 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
241 "Insert a pass after itself!");
242 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
243 Impl->InsertedPasses.push_back(P);
246 /// createPassConfig - Create a pass configuration object to be used by
247 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
249 /// Targets may override this to extend TargetPassConfig.
250 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
251 return new TargetPassConfig(this, PM);
254 TargetPassConfig::TargetPassConfig()
255 : ImmutablePass(ID), PM(nullptr) {
256 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
259 // Helper to verify the analysis is really immutable.
260 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
261 assert(!Initialized && "PassConfig is immutable");
265 void TargetPassConfig::substitutePass(AnalysisID StandardID,
266 IdentifyingPassPtr TargetID) {
267 Impl->TargetPasses[StandardID] = TargetID;
270 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
271 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
272 I = Impl->TargetPasses.find(ID);
273 if (I == Impl->TargetPasses.end())
278 /// Add a pass to the PassManager if that pass is supposed to be run. If the
279 /// Started/Stopped flags indicate either that the compilation should start at
280 /// a later pass or that it should stop after an earlier pass, then do not add
281 /// the pass. Finally, compare the current pass against the StartAfter
282 /// and StopAfter options and change the Started/Stopped flags accordingly.
283 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) {
284 assert(!Initialized && "PassConfig is immutable");
286 // Cache the Pass ID here in case the pass manager finds this pass is
287 // redundant with ones already scheduled / available, and deletes it.
288 // Fundamentally, once we add the pass to the manager, we no longer own it
289 // and shouldn't reference it.
290 AnalysisID PassID = P->getPassID();
292 if (StartBefore == PassID)
294 if (Started && !Stopped) {
296 // Construct banner message before PM->add() as that may delete the pass.
297 if (AddingMachinePasses && (printAfter || verifyAfter))
298 Banner = std::string("After ") + std::string(P->getPassName());
300 if (AddingMachinePasses) {
302 addPrintPass(Banner);
304 addVerifyPass(Banner);
307 // Add the passes after the pass P if there is any.
308 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
309 I = Impl->InsertedPasses.begin(),
310 E = Impl->InsertedPasses.end();
312 if ((*I).first == PassID) {
313 assert((*I).second.isValid() && "Illegal Pass ID!");
315 if ((*I).second.isInstance())
316 NP = (*I).second.getInstance();
318 NP = Pass::createPass((*I).second.getID());
319 assert(NP && "Pass ID not registered");
321 addPass(NP, false, false);
327 if (StopAfter == PassID)
329 if (StartAfter == PassID)
331 if (Stopped && !Started)
332 report_fatal_error("Cannot stop compilation after pass that is not run");
335 /// Add a CodeGen pass at this point in the pipeline after checking for target
336 /// and command line overrides.
338 /// addPass cannot return a pointer to the pass instance because is internal the
339 /// PassManager and the instance we create here may already be freed.
340 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter,
342 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
343 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
344 if (!FinalPtr.isValid())
348 if (FinalPtr.isInstance())
349 P = FinalPtr.getInstance();
351 P = Pass::createPass(FinalPtr.getID());
353 llvm_unreachable("Pass ID not registered");
355 AnalysisID FinalID = P->getPassID();
356 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P.
361 void TargetPassConfig::printAndVerify(const std::string &Banner) {
362 addPrintPass(Banner);
363 addVerifyPass(Banner);
366 void TargetPassConfig::addPrintPass(const std::string &Banner) {
367 if (TM->shouldPrintMachineCode())
368 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner));
371 void TargetPassConfig::addVerifyPass(const std::string &Banner) {
372 if (VerifyMachineCode)
373 PM->add(createMachineVerifierPass(Banner));
376 /// Add common target configurable passes that perform LLVM IR to IR transforms
377 /// following machine independent optimization.
378 void TargetPassConfig::addIRPasses() {
379 // Basic AliasAnalysis support.
380 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
381 // BasicAliasAnalysis wins if they disagree. This is intended to help
382 // support "obvious" type-punning idioms.
384 addPass(createCFLAliasAnalysisPass());
385 addPass(createTypeBasedAliasAnalysisPass());
386 addPass(createScopedNoAliasAAPass());
387 addPass(createBasicAliasAnalysisPass());
389 // Before running any passes, run the verifier to determine if the input
390 // coming from the front-end and/or optimizer is valid.
392 addPass(createVerifierPass());
394 // Run loop strength reduction before anything else.
395 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
396 addPass(createLoopStrengthReducePass());
398 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
401 // Run GC lowering passes for builtin collectors
402 // TODO: add a pass insertion point here
403 addPass(createGCLoweringPass());
404 addPass(createShadowStackGCLoweringPass());
406 // Make sure that no unreachable blocks are instruction selected.
407 addPass(createUnreachableBlockEliminationPass());
409 // Prepare expensive constants for SelectionDAG.
410 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
411 addPass(createConstantHoistingPass());
413 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
414 addPass(createPartiallyInlineLibCallsPass());
417 /// Turn exception handling constructs into something the code generators can
419 void TargetPassConfig::addPassesToHandleExceptions() {
420 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
421 case ExceptionHandling::SjLj:
422 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
423 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
424 // catch info can get misplaced when a selector ends up more than one block
425 // removed from the parent invoke(s). This could happen when a landing
426 // pad is shared by multiple invokes and is also a target of a normal
427 // edge from elsewhere.
428 addPass(createSjLjEHPreparePass());
430 case ExceptionHandling::DwarfCFI:
431 case ExceptionHandling::ARM:
432 addPass(createDwarfEHPass(TM));
434 case ExceptionHandling::WinEH:
435 // We support using both GCC-style and MSVC-style exceptions on Windows, so
436 // add both preparation passes. Each pass will only actually run if it
437 // recognizes the personality function.
438 addPass(createWinEHPass(TM));
439 addPass(createDwarfEHPass(TM));
441 case ExceptionHandling::None:
442 addPass(createLowerInvokePass());
444 // The lower invoke pass may create unreachable code. Remove it.
445 addPass(createUnreachableBlockEliminationPass());
450 /// Add pass to prepare the LLVM IR for code generation. This should be done
451 /// before exception handling preparation passes.
452 void TargetPassConfig::addCodeGenPrepare() {
453 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
454 addPass(createCodeGenPreparePass(TM));
455 addPass(createRewriteSymbolsPass());
458 /// Add common passes that perform LLVM IR to IR transforms in preparation for
459 /// instruction selection.
460 void TargetPassConfig::addISelPrepare() {
463 // Add both the safe stack and the stack protection passes: each of them will
464 // only protect functions that have corresponding attributes.
465 addPass(createSafeStackPass());
466 addPass(createStackProtectorPass(TM));
469 addPass(createPrintFunctionPass(
470 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
472 // All passes which modify the LLVM IR are now complete; run the verifier
473 // to ensure that the IR is valid.
475 addPass(createVerifierPass());
478 /// Add the complete set of target-independent postISel code generator passes.
480 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
481 /// with nontrivial configuration or multiple passes are broken out below in
482 /// add%Stage routines.
484 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
485 /// addPre/Post methods with empty header implementations allow injecting
486 /// target-specific fixups just before or after major stages. Additionally,
487 /// targets have the flexibility to change pass order within a stage by
488 /// overriding default implementation of add%Stage routines below. Each
489 /// technique has maintainability tradeoffs because alternate pass orders are
490 /// not well supported. addPre/Post works better if the target pass is easily
491 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
492 /// the target should override the stage instead.
494 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
495 /// before/after any target-independent pass. But it's currently overkill.
496 void TargetPassConfig::addMachinePasses() {
497 AddingMachinePasses = true;
499 // Insert a machine instr printer pass after the specified pass.
500 // If -print-machineinstrs specified, print machineinstrs after all passes.
501 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
502 TM->Options.PrintMachineCode = true;
503 else if (!StringRef(PrintMachineInstrs.getValue())
504 .equals("option-unspecified")) {
505 const PassRegistry *PR = PassRegistry::getPassRegistry();
506 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
507 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer"));
508 assert (TPI && IPI && "Pass ID not registered!");
509 const char *TID = (const char *)(TPI->getTypeInfo());
510 const char *IID = (const char *)(IPI->getTypeInfo());
511 insertPass(TID, IID);
514 // Print the instruction selected machine code...
515 printAndVerify("After Instruction Selection");
517 // Expand pseudo-instructions emitted by ISel.
518 addPass(&ExpandISelPseudosID);
520 // Add passes that optimize machine instructions in SSA form.
521 if (getOptLevel() != CodeGenOpt::None) {
522 addMachineSSAOptimization();
524 // If the target requests it, assign local variables to stack slots relative
525 // to one another and simplify frame index references where possible.
526 addPass(&LocalStackSlotAllocationID, false);
529 // Run pre-ra passes.
532 // Run register allocation and passes that are tightly coupled with it,
533 // including phi elimination and scheduling.
534 if (getOptimizeRegAlloc())
535 addOptimizedRegAlloc(createRegAllocPass(true));
537 addFastRegAlloc(createRegAllocPass(false));
539 // Run post-ra passes.
542 // Insert prolog/epilog code. Eliminate abstract frame index references...
543 if (getEnableShrinkWrap())
544 addPass(&ShrinkWrapID);
545 addPass(&PrologEpilogCodeInserterID);
547 /// Add passes that optimize machine instructions after register allocation.
548 if (getOptLevel() != CodeGenOpt::None)
549 addMachineLateOptimization();
551 // Expand pseudo instructions before second scheduling pass.
552 addPass(&ExpandPostRAPseudosID);
554 // Run pre-sched2 passes.
557 if (EnableImplicitNullChecks)
558 addPass(&ImplicitNullChecksID);
560 // Second pass scheduler.
561 if (getOptLevel() != CodeGenOpt::None) {
563 addPass(&PostMachineSchedulerID);
565 addPass(&PostRASchedulerID);
571 addPass(createGCInfoPrinter(dbgs()), false, false);
574 // Basic block placement.
575 if (getOptLevel() != CodeGenOpt::None)
580 addPass(&StackMapLivenessID, false);
582 AddingMachinePasses = false;
585 /// Add passes that optimize machine instructions in SSA form.
586 void TargetPassConfig::addMachineSSAOptimization() {
587 // Pre-ra tail duplication.
588 addPass(&EarlyTailDuplicateID);
590 // Optimize PHIs before DCE: removing dead PHI cycles may make more
591 // instructions dead.
592 addPass(&OptimizePHIsID, false);
594 // This pass merges large allocas. StackSlotColoring is a different pass
595 // which merges spill slots.
596 addPass(&StackColoringID, false);
598 // If the target requests it, assign local variables to stack slots relative
599 // to one another and simplify frame index references where possible.
600 addPass(&LocalStackSlotAllocationID, false);
602 // With optimization, dead code should already be eliminated. However
603 // there is one known exception: lowered code for arguments that are only
604 // used by tail calls, where the tail calls reuse the incoming stack
605 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
606 addPass(&DeadMachineInstructionElimID);
608 // Allow targets to insert passes that improve instruction level parallelism,
609 // like if-conversion. Such passes will typically need dominator trees and
610 // loop info, just like LICM and CSE below.
613 addPass(&MachineLICMID, false);
614 addPass(&MachineCSEID, false);
615 addPass(&MachineSinkingID);
617 addPass(&PeepholeOptimizerID, false);
618 // Clean-up the dead code that may have been generated by peephole
620 addPass(&DeadMachineInstructionElimID);
623 bool TargetPassConfig::getEnableShrinkWrap() const {
624 switch (EnableShrinkWrapOpt) {
626 return EnableShrinkWrap && getOptLevel() != CodeGenOpt::None;
627 // If EnableShrinkWrap is set, it takes precedence on whatever the
628 // target sets. The rational is that we assume we want to test
629 // something related to shrink-wrapping.
635 llvm_unreachable("Invalid shrink-wrapping state");
638 //===---------------------------------------------------------------------===//
639 /// Register Allocation Pass Configuration
640 //===---------------------------------------------------------------------===//
642 bool TargetPassConfig::getOptimizeRegAlloc() const {
643 switch (OptimizeRegAlloc) {
644 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
645 case cl::BOU_TRUE: return true;
646 case cl::BOU_FALSE: return false;
648 llvm_unreachable("Invalid optimize-regalloc state");
651 /// RegisterRegAlloc's global Registry tracks allocator registration.
652 MachinePassRegistry RegisterRegAlloc::Registry;
654 /// A dummy default pass factory indicates whether the register allocator is
655 /// overridden on the command line.
656 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
657 static RegisterRegAlloc
658 defaultRegAlloc("default",
659 "pick register allocator based on -O option",
660 useDefaultRegisterAllocator);
662 /// -regalloc=... command line option.
663 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
664 RegisterPassParser<RegisterRegAlloc> >
666 cl::init(&useDefaultRegisterAllocator),
667 cl::desc("Register allocator to use"));
670 /// Instantiate the default register allocator pass for this target for either
671 /// the optimized or unoptimized allocation path. This will be added to the pass
672 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
673 /// in the optimized case.
675 /// A target that uses the standard regalloc pass order for fast or optimized
676 /// allocation may still override this for per-target regalloc
677 /// selection. But -regalloc=... always takes precedence.
678 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
680 return createGreedyRegisterAllocator();
682 return createFastRegisterAllocator();
685 /// Find and instantiate the register allocation pass requested by this target
686 /// at the current optimization level. Different register allocators are
687 /// defined as separate passes because they may require different analysis.
689 /// This helper ensures that the regalloc= option is always available,
690 /// even for targets that override the default allocator.
692 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
693 /// this can be folded into addPass.
694 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
695 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
697 // Initialize the global default.
700 RegisterRegAlloc::setDefault(RegAlloc);
702 if (Ctor != useDefaultRegisterAllocator)
705 // With no -regalloc= override, ask the target for a regalloc pass.
706 return createTargetRegisterAllocator(Optimized);
709 /// Return true if the default global register allocator is in use and
710 /// has not be overriden on the command line with '-regalloc=...'
711 bool TargetPassConfig::usingDefaultRegAlloc() const {
712 return RegAlloc.getNumOccurrences() == 0;
715 /// Add the minimum set of target-independent passes that are required for
716 /// register allocation. No coalescing or scheduling.
717 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
718 addPass(&PHIEliminationID, false);
719 addPass(&TwoAddressInstructionPassID, false);
721 addPass(RegAllocPass);
724 /// Add standard target-independent passes that are tightly coupled with
725 /// optimized register allocation, including coalescing, machine instruction
726 /// scheduling, and register allocation itself.
727 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
728 addPass(&ProcessImplicitDefsID, false);
730 // LiveVariables currently requires pure SSA form.
732 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
733 // LiveVariables can be removed completely, and LiveIntervals can be directly
734 // computed. (We still either need to regenerate kill flags after regalloc, or
735 // preferably fix the scavenger to not depend on them).
736 addPass(&LiveVariablesID, false);
738 // Edge splitting is smarter with machine loop info.
739 addPass(&MachineLoopInfoID, false);
740 addPass(&PHIEliminationID, false);
742 // Eventually, we want to run LiveIntervals before PHI elimination.
743 if (EarlyLiveIntervals)
744 addPass(&LiveIntervalsID, false);
746 addPass(&TwoAddressInstructionPassID, false);
747 addPass(&RegisterCoalescerID);
749 // PreRA instruction scheduling.
750 addPass(&MachineSchedulerID);
752 // Add the selected register allocation pass.
753 addPass(RegAllocPass);
755 // Allow targets to change the register assignments before rewriting.
758 // Finally rewrite virtual registers.
759 addPass(&VirtRegRewriterID);
761 // Perform stack slot coloring and post-ra machine LICM.
763 // FIXME: Re-enable coloring with register when it's capable of adding
765 addPass(&StackSlotColoringID);
767 // Run post-ra machine LICM to hoist reloads / remats.
769 // FIXME: can this move into MachineLateOptimization?
770 addPass(&PostRAMachineLICMID);
773 //===---------------------------------------------------------------------===//
774 /// Post RegAlloc Pass Configuration
775 //===---------------------------------------------------------------------===//
777 /// Add passes that optimize machine instructions after register allocation.
778 void TargetPassConfig::addMachineLateOptimization() {
779 // Branch folding must be run after regalloc and prolog/epilog insertion.
780 addPass(&BranchFolderPassID);
783 // Note that duplicating tail just increases code size and degrades
784 // performance for targets that require Structured Control Flow.
785 // In addition it can also make CFG irreducible. Thus we disable it.
786 if (!TM->requiresStructuredCFG())
787 addPass(&TailDuplicateID);
790 addPass(&MachineCopyPropagationID);
793 /// Add standard GC passes.
794 bool TargetPassConfig::addGCPasses() {
795 addPass(&GCMachineCodeAnalysisID, false);
799 /// Add standard basic block placement passes.
800 void TargetPassConfig::addBlockPlacement() {
801 if (addPass(&MachineBlockPlacementID, false)) {
802 // Run a separate pass to collect block placement statistics.
803 if (EnableBlockPlacementStats)
804 addPass(&MachineBlockPlacementStatsID);