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/GCStrategy.h"
18 #include "llvm/CodeGen/MachineFunctionPass.h"
19 #include "llvm/CodeGen/RegAllocRegistry.h"
20 #include "llvm/IR/IRPrintingPasses.h"
21 #include "llvm/IR/Verifier.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"
33 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
34 cl::desc("Disable Post Regalloc"));
35 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
36 cl::desc("Disable branch folding"));
37 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
38 cl::desc("Disable tail duplication"));
39 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
40 cl::desc("Disable pre-register allocation tail duplication"));
41 static cl::opt<bool> DisableBlockPlacement("disable-block-placement",
42 cl::Hidden, cl::desc("Disable probability-driven block placement"));
43 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
44 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
45 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
46 cl::desc("Disable Stack Slot Coloring"));
47 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
48 cl::desc("Disable Machine Dead Code Elimination"));
49 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden,
50 cl::desc("Disable Early If-conversion"));
51 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
52 cl::desc("Disable Machine LICM"));
53 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
54 cl::desc("Disable Machine Common Subexpression Elimination"));
55 static cl::opt<cl::boolOrDefault>
56 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
57 cl::desc("Enable optimized register allocation compilation path."));
58 static cl::opt<cl::boolOrDefault>
59 EnableMachineSched("enable-misched",
60 cl::desc("Enable the machine instruction scheduling pass."));
61 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
63 cl::desc("Disable Machine LICM"));
64 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
65 cl::desc("Disable Machine Sinking"));
66 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
67 cl::desc("Disable Loop Strength Reduction Pass"));
68 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting",
69 cl::Hidden, cl::desc("Disable ConstantHoisting"));
70 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
71 cl::desc("Disable Codegen Prepare"));
72 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
73 cl::desc("Disable Copy Propagation pass"));
74 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining",
75 cl::Hidden, cl::desc("Disable Partial Libcall Inlining"));
76 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
77 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
78 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
79 cl::desc("Print LLVM IR input to isel pass"));
80 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
81 cl::desc("Dump garbage collector data"));
82 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
83 cl::desc("Verify generated machine code"),
84 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=nullptr));
85 static cl::opt<std::string>
86 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional,
87 cl::desc("Print machine instrs"),
88 cl::value_desc("pass-name"), cl::init("option-unspecified"));
90 // Temporary option to allow experimenting with MachineScheduler as a post-RA
91 // scheduler. Targets can "properly" enable this with
92 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID); Ideally it
93 // wouldn't be part of the standard pass pipeline, and the target would just add
94 // a PostRA scheduling pass wherever it wants.
95 static cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden,
96 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)"));
98 // Experimental option to run live interval analysis early.
99 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden,
100 cl::desc("Run live interval analysis earlier in the pipeline"));
102 static cl::opt<bool> UseCFLAA("use-cfl-aa-in-codegen",
103 cl::init(false), cl::Hidden,
104 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"));
106 /// Allow standard passes to be disabled by command line options. This supports
107 /// simple binary flags that either suppress the pass or do nothing.
108 /// i.e. -disable-mypass=false has no effect.
109 /// These should be converted to boolOrDefault in order to use applyOverride.
110 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID,
113 return IdentifyingPassPtr();
117 /// Allow Pass selection to be overriden by command line options. This supports
118 /// flags with ternary conditions. TargetID is passed through by default. The
119 /// pass is suppressed when the option is false. When the option is true, the
120 /// StandardID is selected if the target provides no default.
121 static IdentifyingPassPtr applyOverride(IdentifyingPassPtr TargetID,
122 cl::boolOrDefault Override,
123 AnalysisID StandardID) {
128 if (TargetID.isValid())
130 if (StandardID == nullptr)
131 report_fatal_error("Target cannot enable pass");
134 return IdentifyingPassPtr();
136 llvm_unreachable("Invalid command line option state");
139 /// Allow standard passes to be disabled by the command line, regardless of who
140 /// is adding the pass.
142 /// StandardID is the pass identified in the standard pass pipeline and provided
143 /// to addPass(). It may be a target-specific ID in the case that the target
144 /// directly adds its own pass, but in that case we harmlessly fall through.
146 /// TargetID is the pass that the target has configured to override StandardID.
148 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real
149 /// pass to run. This allows multiple options to control a single pass depending
150 /// on where in the pipeline that pass is added.
151 static IdentifyingPassPtr overridePass(AnalysisID StandardID,
152 IdentifyingPassPtr TargetID) {
153 if (StandardID == &PostRASchedulerID)
154 return applyDisable(TargetID, DisablePostRA);
156 if (StandardID == &BranchFolderPassID)
157 return applyDisable(TargetID, DisableBranchFold);
159 if (StandardID == &TailDuplicateID)
160 return applyDisable(TargetID, DisableTailDuplicate);
162 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID)
163 return applyDisable(TargetID, DisableEarlyTailDup);
165 if (StandardID == &MachineBlockPlacementID)
166 return applyDisable(TargetID, DisableBlockPlacement);
168 if (StandardID == &StackSlotColoringID)
169 return applyDisable(TargetID, DisableSSC);
171 if (StandardID == &DeadMachineInstructionElimID)
172 return applyDisable(TargetID, DisableMachineDCE);
174 if (StandardID == &EarlyIfConverterID)
175 return applyDisable(TargetID, DisableEarlyIfConversion);
177 if (StandardID == &MachineLICMID)
178 return applyDisable(TargetID, DisableMachineLICM);
180 if (StandardID == &MachineCSEID)
181 return applyDisable(TargetID, DisableMachineCSE);
183 if (StandardID == &MachineSchedulerID)
184 return applyOverride(TargetID, EnableMachineSched, StandardID);
186 if (StandardID == &TargetPassConfig::PostRAMachineLICMID)
187 return applyDisable(TargetID, DisablePostRAMachineLICM);
189 if (StandardID == &MachineSinkingID)
190 return applyDisable(TargetID, DisableMachineSink);
192 if (StandardID == &MachineCopyPropagationID)
193 return applyDisable(TargetID, DisableCopyProp);
198 //===---------------------------------------------------------------------===//
200 //===---------------------------------------------------------------------===//
202 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
203 "Target Pass Configuration", false, false)
204 char TargetPassConfig::ID = 0;
207 char TargetPassConfig::EarlyTailDuplicateID = 0;
208 char TargetPassConfig::PostRAMachineLICMID = 0;
211 class PassConfigImpl {
213 // List of passes explicitly substituted by this target. Normally this is
214 // empty, but it is a convenient way to suppress or replace specific passes
215 // that are part of a standard pass pipeline without overridding the entire
216 // pipeline. This mechanism allows target options to inherit a standard pass's
217 // user interface. For example, a target may disable a standard pass by
218 // default by substituting a pass ID of zero, and the user may still enable
219 // that standard pass with an explicit command line option.
220 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses;
222 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass
223 /// is inserted after each instance of the first one.
224 SmallVector<std::pair<AnalysisID, IdentifyingPassPtr>, 4> InsertedPasses;
228 // Out of line virtual method.
229 TargetPassConfig::~TargetPassConfig() {
233 // Out of line constructor provides default values for pass options and
234 // registers all common codegen passes.
235 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
236 : ImmutablePass(ID), PM(&pm), StartAfter(nullptr), StopAfter(nullptr),
237 Started(true), Stopped(false), TM(tm), Impl(nullptr), Initialized(false),
238 DisableVerify(false),
239 EnableTailMerge(true) {
241 Impl = new PassConfigImpl();
243 // Register all target independent codegen passes to activate their PassIDs,
244 // including this pass itself.
245 initializeCodeGen(*PassRegistry::getPassRegistry());
247 // Substitute Pseudo Pass IDs for real ones.
248 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID);
249 substitutePass(&PostRAMachineLICMID, &MachineLICMID);
251 // Temporarily disable experimental passes.
252 const TargetSubtargetInfo &ST = TM->getSubtarget<TargetSubtargetInfo>();
253 if (!ST.useMachineScheduler())
254 disablePass(&MachineSchedulerID);
257 /// Insert InsertedPassID pass after TargetPassID.
258 void TargetPassConfig::insertPass(AnalysisID TargetPassID,
259 IdentifyingPassPtr InsertedPassID) {
260 assert(((!InsertedPassID.isInstance() &&
261 TargetPassID != InsertedPassID.getID()) ||
262 (InsertedPassID.isInstance() &&
263 TargetPassID != InsertedPassID.getInstance()->getPassID())) &&
264 "Insert a pass after itself!");
265 std::pair<AnalysisID, IdentifyingPassPtr> P(TargetPassID, InsertedPassID);
266 Impl->InsertedPasses.push_back(P);
269 /// createPassConfig - Create a pass configuration object to be used by
270 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
272 /// Targets may override this to extend TargetPassConfig.
273 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
274 return new TargetPassConfig(this, PM);
277 TargetPassConfig::TargetPassConfig()
278 : ImmutablePass(ID), PM(nullptr) {
279 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
282 // Helper to verify the analysis is really immutable.
283 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
284 assert(!Initialized && "PassConfig is immutable");
288 void TargetPassConfig::substitutePass(AnalysisID StandardID,
289 IdentifyingPassPtr TargetID) {
290 Impl->TargetPasses[StandardID] = TargetID;
293 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const {
294 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator
295 I = Impl->TargetPasses.find(ID);
296 if (I == Impl->TargetPasses.end())
301 /// Add a pass to the PassManager if that pass is supposed to be run. If the
302 /// Started/Stopped flags indicate either that the compilation should start at
303 /// a later pass or that it should stop after an earlier pass, then do not add
304 /// the pass. Finally, compare the current pass against the StartAfter
305 /// and StopAfter options and change the Started/Stopped flags accordingly.
306 void TargetPassConfig::addPass(Pass *P) {
307 assert(!Initialized && "PassConfig is immutable");
309 // Cache the Pass ID here in case the pass manager finds this pass is
310 // redundant with ones already scheduled / available, and deletes it.
311 // Fundamentally, once we add the pass to the manager, we no longer own it
312 // and shouldn't reference it.
313 AnalysisID PassID = P->getPassID();
315 if (Started && !Stopped)
319 if (StopAfter == PassID)
321 if (StartAfter == PassID)
323 if (Stopped && !Started)
324 report_fatal_error("Cannot stop compilation after pass that is not run");
327 /// Add a CodeGen pass at this point in the pipeline after checking for target
328 /// and command line overrides.
330 /// addPass cannot return a pointer to the pass instance because is internal the
331 /// PassManager and the instance we create here may already be freed.
332 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) {
333 IdentifyingPassPtr TargetID = getPassSubstitution(PassID);
334 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID);
335 if (!FinalPtr.isValid())
339 if (FinalPtr.isInstance())
340 P = FinalPtr.getInstance();
342 P = Pass::createPass(FinalPtr.getID());
344 llvm_unreachable("Pass ID not registered");
346 AnalysisID FinalID = P->getPassID();
347 addPass(P); // Ends the lifetime of P.
349 // Add the passes after the pass P if there is any.
350 for (SmallVectorImpl<std::pair<AnalysisID, IdentifyingPassPtr> >::iterator
351 I = Impl->InsertedPasses.begin(), E = Impl->InsertedPasses.end();
353 if ((*I).first == PassID) {
354 assert((*I).second.isValid() && "Illegal Pass ID!");
356 if ((*I).second.isInstance())
357 NP = (*I).second.getInstance();
359 NP = Pass::createPass((*I).second.getID());
360 assert(NP && "Pass ID not registered");
368 void TargetPassConfig::printAndVerify(const char *Banner) {
369 if (TM->shouldPrintMachineCode())
370 addPass(createMachineFunctionPrinterPass(dbgs(), Banner));
372 if (VerifyMachineCode)
373 addPass(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.
391 if (!DisableVerify) {
392 addPass(createVerifierPass());
393 addPass(createDebugInfoVerifierPass());
396 // Run loop strength reduction before anything else.
397 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
398 addPass(createLoopStrengthReducePass());
400 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n"));
403 addPass(createGCLoweringPass());
405 // Make sure that no unreachable blocks are instruction selected.
406 addPass(createUnreachableBlockEliminationPass());
408 // Prepare expensive constants for SelectionDAG.
409 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting)
410 addPass(createConstantHoistingPass());
412 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining)
413 addPass(createPartiallyInlineLibCallsPass());
416 /// Turn exception handling constructs into something the code generators can
418 void TargetPassConfig::addPassesToHandleExceptions() {
419 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
420 case ExceptionHandling::SjLj:
421 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
422 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
423 // catch info can get misplaced when a selector ends up more than one block
424 // removed from the parent invoke(s). This could happen when a landing
425 // pad is shared by multiple invokes and is also a target of a normal
426 // edge from elsewhere.
427 addPass(createSjLjEHPreparePass(TM));
429 case ExceptionHandling::DwarfCFI:
430 case ExceptionHandling::ARM:
431 case ExceptionHandling::WinEH:
432 addPass(createDwarfEHPass(TM));
434 case ExceptionHandling::None:
435 addPass(createLowerInvokePass());
437 // The lower invoke pass may create unreachable code. Remove it.
438 addPass(createUnreachableBlockEliminationPass());
443 /// Add pass to prepare the LLVM IR for code generation. This should be done
444 /// before exception handling preparation passes.
445 void TargetPassConfig::addCodeGenPrepare() {
446 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
447 addPass(createCodeGenPreparePass(TM));
450 /// Add common passes that perform LLVM IR to IR transforms in preparation for
451 /// instruction selection.
452 void TargetPassConfig::addISelPrepare() {
455 // Need to verify DebugInfo *before* creating the stack protector analysis.
456 // It's a function pass, and verifying between it and its users causes a
459 addPass(createDebugInfoVerifierPass());
461 addPass(createStackProtectorPass(TM));
464 addPass(createPrintFunctionPass(
465 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n"));
467 // All passes which modify the LLVM IR are now complete; run the verifier
468 // to ensure that the IR is valid.
470 addPass(createVerifierPass());
473 /// Add the complete set of target-independent postISel code generator passes.
475 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
476 /// with nontrivial configuration or multiple passes are broken out below in
477 /// add%Stage routines.
479 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
480 /// addPre/Post methods with empty header implementations allow injecting
481 /// target-specific fixups just before or after major stages. Additionally,
482 /// targets have the flexibility to change pass order within a stage by
483 /// overriding default implementation of add%Stage routines below. Each
484 /// technique has maintainability tradeoffs because alternate pass orders are
485 /// not well supported. addPre/Post works better if the target pass is easily
486 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
487 /// the target should override the stage instead.
489 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
490 /// before/after any target-independent pass. But it's currently overkill.
491 void TargetPassConfig::addMachinePasses() {
492 // Insert a machine instr printer pass after the specified pass.
493 // If -print-machineinstrs specified, print machineinstrs after all passes.
494 if (StringRef(PrintMachineInstrs.getValue()).equals(""))
495 TM->Options.PrintMachineCode = true;
496 else if (!StringRef(PrintMachineInstrs.getValue())
497 .equals("option-unspecified")) {
498 const PassRegistry *PR = PassRegistry::getPassRegistry();
499 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue());
500 const PassInfo *IPI = PR->getPassInfo(StringRef("print-machineinstrs"));
501 assert (TPI && IPI && "Pass ID not registered!");
502 const char *TID = (const char *)(TPI->getTypeInfo());
503 const char *IID = (const char *)(IPI->getTypeInfo());
504 insertPass(TID, IID);
507 // Print the instruction selected machine code...
508 printAndVerify("After Instruction Selection");
510 // Expand pseudo-instructions emitted by ISel.
511 if (addPass(&ExpandISelPseudosID))
512 printAndVerify("After ExpandISelPseudos");
514 // Add passes that optimize machine instructions in SSA form.
515 if (getOptLevel() != CodeGenOpt::None) {
516 addMachineSSAOptimization();
518 // If the target requests it, assign local variables to stack slots relative
519 // to one another and simplify frame index references where possible.
520 addPass(&LocalStackSlotAllocationID);
523 // Run pre-ra passes.
524 if (addPreRegAlloc())
525 printAndVerify("After PreRegAlloc passes");
527 // Run register allocation and passes that are tightly coupled with it,
528 // including phi elimination and scheduling.
529 if (getOptimizeRegAlloc())
530 addOptimizedRegAlloc(createRegAllocPass(true));
532 addFastRegAlloc(createRegAllocPass(false));
534 // Run post-ra passes.
535 if (addPostRegAlloc())
536 printAndVerify("After PostRegAlloc passes");
538 // Insert prolog/epilog code. Eliminate abstract frame index references...
539 addPass(&PrologEpilogCodeInserterID);
540 printAndVerify("After PrologEpilogCodeInserter");
542 /// Add passes that optimize machine instructions after register allocation.
543 if (getOptLevel() != CodeGenOpt::None)
544 addMachineLateOptimization();
546 // Expand pseudo instructions before second scheduling pass.
547 addPass(&ExpandPostRAPseudosID);
548 printAndVerify("After ExpandPostRAPseudos");
550 // Run pre-sched2 passes.
552 printAndVerify("After PreSched2 passes");
554 // Second pass scheduler.
555 if (getOptLevel() != CodeGenOpt::None) {
557 addPass(&PostMachineSchedulerID);
559 addPass(&PostRASchedulerID);
560 printAndVerify("After PostRAScheduler");
566 addPass(createGCInfoPrinter(dbgs()));
569 // Basic block placement.
570 if (getOptLevel() != CodeGenOpt::None)
573 if (addPreEmitPass())
574 printAndVerify("After PreEmit passes");
576 addPass(&StackMapLivenessID);
579 /// Add passes that optimize machine instructions in SSA form.
580 void TargetPassConfig::addMachineSSAOptimization() {
581 // Pre-ra tail duplication.
582 if (addPass(&EarlyTailDuplicateID))
583 printAndVerify("After Pre-RegAlloc TailDuplicate");
585 // Optimize PHIs before DCE: removing dead PHI cycles may make more
586 // instructions dead.
587 addPass(&OptimizePHIsID);
589 // This pass merges large allocas. StackSlotColoring is a different pass
590 // which merges spill slots.
591 addPass(&StackColoringID);
593 // If the target requests it, assign local variables to stack slots relative
594 // to one another and simplify frame index references where possible.
595 addPass(&LocalStackSlotAllocationID);
597 // With optimization, dead code should already be eliminated. However
598 // there is one known exception: lowered code for arguments that are only
599 // used by tail calls, where the tail calls reuse the incoming stack
600 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
601 addPass(&DeadMachineInstructionElimID);
602 printAndVerify("After codegen DCE pass");
604 // Allow targets to insert passes that improve instruction level parallelism,
605 // like if-conversion. Such passes will typically need dominator trees and
606 // loop info, just like LICM and CSE below.
608 printAndVerify("After ILP optimizations");
610 addPass(&MachineLICMID);
611 addPass(&MachineCSEID);
612 addPass(&MachineSinkingID);
613 printAndVerify("After Machine LICM, CSE and Sinking passes");
615 addPass(&PeepholeOptimizerID);
616 // Clean-up the dead code that may have been generated by peephole
618 addPass(&DeadMachineInstructionElimID);
619 printAndVerify("After codegen peephole optimization pass");
622 //===---------------------------------------------------------------------===//
623 /// Register Allocation Pass Configuration
624 //===---------------------------------------------------------------------===//
626 bool TargetPassConfig::getOptimizeRegAlloc() const {
627 switch (OptimizeRegAlloc) {
628 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
629 case cl::BOU_TRUE: return true;
630 case cl::BOU_FALSE: return false;
632 llvm_unreachable("Invalid optimize-regalloc state");
635 /// RegisterRegAlloc's global Registry tracks allocator registration.
636 MachinePassRegistry RegisterRegAlloc::Registry;
638 /// A dummy default pass factory indicates whether the register allocator is
639 /// overridden on the command line.
640 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; }
641 static RegisterRegAlloc
642 defaultRegAlloc("default",
643 "pick register allocator based on -O option",
644 useDefaultRegisterAllocator);
646 /// -regalloc=... command line option.
647 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
648 RegisterPassParser<RegisterRegAlloc> >
650 cl::init(&useDefaultRegisterAllocator),
651 cl::desc("Register allocator to use"));
654 /// Instantiate the default register allocator pass for this target for either
655 /// the optimized or unoptimized allocation path. This will be added to the pass
656 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
657 /// in the optimized case.
659 /// A target that uses the standard regalloc pass order for fast or optimized
660 /// allocation may still override this for per-target regalloc
661 /// selection. But -regalloc=... always takes precedence.
662 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
664 return createGreedyRegisterAllocator();
666 return createFastRegisterAllocator();
669 /// Find and instantiate the register allocation pass requested by this target
670 /// at the current optimization level. Different register allocators are
671 /// defined as separate passes because they may require different analysis.
673 /// This helper ensures that the regalloc= option is always available,
674 /// even for targets that override the default allocator.
676 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
677 /// this can be folded into addPass.
678 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
679 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
681 // Initialize the global default.
684 RegisterRegAlloc::setDefault(RegAlloc);
686 if (Ctor != useDefaultRegisterAllocator)
689 // With no -regalloc= override, ask the target for a regalloc pass.
690 return createTargetRegisterAllocator(Optimized);
693 /// Add the minimum set of target-independent passes that are required for
694 /// register allocation. No coalescing or scheduling.
695 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
696 addPass(&PHIEliminationID);
697 addPass(&TwoAddressInstructionPassID);
699 addPass(RegAllocPass);
700 printAndVerify("After Register Allocation");
703 /// Add standard target-independent passes that are tightly coupled with
704 /// optimized register allocation, including coalescing, machine instruction
705 /// scheduling, and register allocation itself.
706 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
707 addPass(&ProcessImplicitDefsID);
709 // LiveVariables currently requires pure SSA form.
711 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
712 // LiveVariables can be removed completely, and LiveIntervals can be directly
713 // computed. (We still either need to regenerate kill flags after regalloc, or
714 // preferably fix the scavenger to not depend on them).
715 addPass(&LiveVariablesID);
717 // Edge splitting is smarter with machine loop info.
718 addPass(&MachineLoopInfoID);
719 addPass(&PHIEliminationID);
721 // Eventually, we want to run LiveIntervals before PHI elimination.
722 if (EarlyLiveIntervals)
723 addPass(&LiveIntervalsID);
725 addPass(&TwoAddressInstructionPassID);
726 addPass(&RegisterCoalescerID);
728 // PreRA instruction scheduling.
729 if (addPass(&MachineSchedulerID))
730 printAndVerify("After Machine Scheduling");
732 // Add the selected register allocation pass.
733 addPass(RegAllocPass);
734 printAndVerify("After Register Allocation, before rewriter");
736 // Allow targets to change the register assignments before rewriting.
738 printAndVerify("After pre-rewrite passes");
740 // Finally rewrite virtual registers.
741 addPass(&VirtRegRewriterID);
742 printAndVerify("After Virtual Register Rewriter");
744 // Perform stack slot coloring and post-ra machine LICM.
746 // FIXME: Re-enable coloring with register when it's capable of adding
748 addPass(&StackSlotColoringID);
750 // Run post-ra machine LICM to hoist reloads / remats.
752 // FIXME: can this move into MachineLateOptimization?
753 addPass(&PostRAMachineLICMID);
755 printAndVerify("After StackSlotColoring and postra Machine LICM");
758 //===---------------------------------------------------------------------===//
759 /// Post RegAlloc Pass Configuration
760 //===---------------------------------------------------------------------===//
762 /// Add passes that optimize machine instructions after register allocation.
763 void TargetPassConfig::addMachineLateOptimization() {
764 // Branch folding must be run after regalloc and prolog/epilog insertion.
765 if (addPass(&BranchFolderPassID))
766 printAndVerify("After BranchFolding");
769 // Note that duplicating tail just increases code size and degrades
770 // performance for targets that require Structured Control Flow.
771 // In addition it can also make CFG irreducible. Thus we disable it.
772 if (!TM->requiresStructuredCFG() && addPass(&TailDuplicateID))
773 printAndVerify("After TailDuplicate");
776 if (addPass(&MachineCopyPropagationID))
777 printAndVerify("After copy propagation pass");
780 /// Add standard GC passes.
781 bool TargetPassConfig::addGCPasses() {
782 addPass(&GCMachineCodeAnalysisID);
786 /// Add standard basic block placement passes.
787 void TargetPassConfig::addBlockPlacement() {
788 if (addPass(&MachineBlockPlacementID)) {
789 // Run a separate pass to collect block placement statistics.
790 if (EnableBlockPlacementStats)
791 addPass(&MachineBlockPlacementStatsID);
793 printAndVerify("After machine block placement.");