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/Analysis/Passes.h"
16 #include "llvm/Analysis/Verifier.h"
17 #include "llvm/Transforms/Scalar.h"
18 #include "llvm/PassManager.h"
19 #include "llvm/CodeGen/GCStrategy.h"
20 #include "llvm/CodeGen/MachineFunctionPass.h"
21 #include "llvm/CodeGen/Passes.h"
22 #include "llvm/CodeGen/RegAllocRegistry.h"
23 #include "llvm/Target/TargetLowering.h"
24 #include "llvm/Target/TargetOptions.h"
25 #include "llvm/Assembly/PrintModulePass.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/ErrorHandling.h"
32 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
33 cl::desc("Disable Post Regalloc"));
34 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
35 cl::desc("Disable branch folding"));
36 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
37 cl::desc("Disable tail duplication"));
38 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
39 cl::desc("Disable pre-register allocation tail duplication"));
40 static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
41 cl::Hidden, cl::desc("Enable probability-driven block placement"));
42 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
43 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
44 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
45 cl::desc("Disable code placement"));
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> DisableMachineLICM("disable-machine-licm", cl::Hidden,
51 cl::desc("Disable Machine LICM"));
52 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
53 cl::desc("Disable Machine Common Subexpression Elimination"));
54 static cl::opt<cl::boolOrDefault>
55 OptimizeRegAlloc("optimize-regalloc", cl::Hidden,
56 cl::desc("Enable optimized register allocation compilation path."));
57 static cl::opt<bool> EnableMachineSched("enable-misched", cl::Hidden,
58 cl::desc("Enable the machine instruction scheduling pass."));
59 static cl::opt<bool> EnableStrongPHIElim("strong-phi-elim", cl::Hidden,
60 cl::desc("Use strong PHI elimination."));
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> DisableCGP("disable-cgp", cl::Hidden,
69 cl::desc("Disable Codegen Prepare"));
70 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
71 cl::desc("Disable Copy Propagation pass"));
72 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
73 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
74 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
75 cl::desc("Print LLVM IR input to isel pass"));
76 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
77 cl::desc("Dump garbage collector data"));
78 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
79 cl::desc("Verify generated machine code"),
80 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
82 //===---------------------------------------------------------------------===//
84 //===---------------------------------------------------------------------===//
86 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
87 "Target Pass Configuration", false, false)
88 char TargetPassConfig::ID = 0;
90 // Out of line virtual method.
91 TargetPassConfig::~TargetPassConfig() {}
93 // Out of line constructor provides default values for pass options and
94 // registers all common codegen passes.
95 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
96 : ImmutablePass(ID), TM(tm), PM(pm), Initialized(false),
98 EnableTailMerge(true) {
100 // Register all target independent codegen passes to activate their PassIDs,
101 // including this pass itself.
102 initializeCodeGen(*PassRegistry::getPassRegistry());
105 /// createPassConfig - Create a pass configuration object to be used by
106 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
108 /// Targets may override this to extend TargetPassConfig.
109 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
110 return new TargetPassConfig(this, PM);
113 TargetPassConfig::TargetPassConfig()
114 : ImmutablePass(ID), PM(*(PassManagerBase*)0) {
115 llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
118 // Helper to verify the analysis is really immutable.
119 void TargetPassConfig::setOpt(bool &Opt, bool Val) {
120 assert(!Initialized && "PassConfig is immutable");
124 void TargetPassConfig::addPass(char &ID) {
125 // FIXME: check user overrides
126 Pass *P = Pass::createPass(ID);
128 llvm_unreachable("Pass ID not registered");
132 void TargetPassConfig::printNoVerify(const char *Banner) const {
133 if (TM->shouldPrintMachineCode())
134 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
137 void TargetPassConfig::printAndVerify(const char *Banner) const {
138 if (TM->shouldPrintMachineCode())
139 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
141 if (VerifyMachineCode)
142 PM.add(createMachineVerifierPass(Banner));
145 /// Add common target configurable passes that perform LLVM IR to IR transforms
146 /// following machine independent optimization.
147 void TargetPassConfig::addIRPasses() {
148 // Basic AliasAnalysis support.
149 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
150 // BasicAliasAnalysis wins if they disagree. This is intended to help
151 // support "obvious" type-punning idioms.
152 PM.add(createTypeBasedAliasAnalysisPass());
153 PM.add(createBasicAliasAnalysisPass());
155 // Before running any passes, run the verifier to determine if the input
156 // coming from the front-end and/or optimizer is valid.
158 PM.add(createVerifierPass());
160 // Run loop strength reduction before anything else.
161 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
162 PM.add(createLoopStrengthReducePass(getTargetLowering()));
164 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
167 PM.add(createGCLoweringPass());
169 // Make sure that no unreachable blocks are instruction selected.
170 PM.add(createUnreachableBlockEliminationPass());
173 /// Add common passes that perform LLVM IR to IR transforms in preparation for
174 /// instruction selection.
175 void TargetPassConfig::addISelPrepare() {
176 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
177 PM.add(createCodeGenPreparePass(getTargetLowering()));
179 PM.add(createStackProtectorPass(getTargetLowering()));
184 PM.add(createPrintFunctionPass("\n\n"
185 "*** Final LLVM Code input to ISel ***\n",
188 // All passes which modify the LLVM IR are now complete; run the verifier
189 // to ensure that the IR is valid.
191 PM.add(createVerifierPass());
194 /// Add the complete set of target-independent postISel code generator passes.
196 /// This can be read as the standard order of major LLVM CodeGen stages. Stages
197 /// with nontrivial configuration or multiple passes are broken out below in
198 /// add%Stage routines.
200 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The
201 /// addPre/Post methods with empty header implementations allow injecting
202 /// target-specific fixups just before or after major stages. Additionally,
203 /// targets have the flexibility to change pass order within a stage by
204 /// overriding default implementation of add%Stage routines below. Each
205 /// technique has maintainability tradeoffs because alternate pass orders are
206 /// not well supported. addPre/Post works better if the target pass is easily
207 /// tied to a common pass. But if it has subtle dependencies on multiple passes,
208 /// the target should override the stage instead.
210 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection
211 /// before/after any target-independent pass. But it's currently overkill.
212 void TargetPassConfig::addMachinePasses() {
213 // Print the instruction selected machine code...
214 printAndVerify("After Instruction Selection");
216 // Expand pseudo-instructions emitted by ISel.
217 addPass(ExpandISelPseudosID);
219 // Add passes that optimize machine instructions in SSA form.
220 if (getOptLevel() != CodeGenOpt::None) {
221 addMachineSSAOptimization();
224 // If the target requests it, assign local variables to stack slots relative
225 // to one another and simplify frame index references where possible.
226 addPass(LocalStackSlotAllocationID);
229 // Run pre-ra passes.
230 if (addPreRegAlloc())
231 printAndVerify("After PreRegAlloc passes");
233 // Run register allocation and passes that are tightly coupled with it,
234 // including phi elimination and scheduling.
235 if (getOptimizeRegAlloc())
236 addOptimizedRegAlloc(createRegAllocPass(true));
238 addFastRegAlloc(createRegAllocPass(false));
240 // Run post-ra passes.
241 if (addPostRegAlloc())
242 printAndVerify("After PostRegAlloc passes");
244 // Insert prolog/epilog code. Eliminate abstract frame index references...
245 addPass(PrologEpilogCodeInserterID);
246 printAndVerify("After PrologEpilogCodeInserter");
248 /// Add passes that optimize machine instructions after register allocation.
249 if (getOptLevel() != CodeGenOpt::None)
250 addMachineLateOptimization();
252 // Expand pseudo instructions before second scheduling pass.
253 addPass(ExpandPostRAPseudosID);
254 printNoVerify("After ExpandPostRAPseudos");
256 // Run pre-sched2 passes.
258 printNoVerify("After PreSched2 passes");
260 // Second pass scheduler.
261 if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
262 addPass(PostRASchedulerID);
263 printNoVerify("After PostRAScheduler");
267 addPass(GCMachineCodeAnalysisID);
269 PM.add(createGCInfoPrinter(dbgs()));
271 // Basic block placement.
272 if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace)
275 if (addPreEmitPass())
276 printNoVerify("After PreEmit passes");
279 /// Add passes that optimize machine instructions in SSA form.
280 void TargetPassConfig::addMachineSSAOptimization() {
281 // Pre-ra tail duplication.
282 if (!DisableEarlyTailDup) {
283 addPass(TailDuplicateID);
284 printAndVerify("After Pre-RegAlloc TailDuplicate");
287 // Optimize PHIs before DCE: removing dead PHI cycles may make more
288 // instructions dead.
289 addPass(OptimizePHIsID);
291 // If the target requests it, assign local variables to stack slots relative
292 // to one another and simplify frame index references where possible.
293 addPass(LocalStackSlotAllocationID);
295 // With optimization, dead code should already be eliminated. However
296 // there is one known exception: lowered code for arguments that are only
297 // used by tail calls, where the tail calls reuse the incoming stack
298 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
299 if (!DisableMachineDCE)
300 addPass(DeadMachineInstructionElimID);
301 printAndVerify("After codegen DCE pass");
303 if (!DisableMachineLICM)
304 addPass(MachineLICMID);
305 if (!DisableMachineCSE)
306 addPass(MachineCSEID);
307 if (!DisableMachineSink)
308 addPass(MachineSinkingID);
309 printAndVerify("After Machine LICM, CSE and Sinking passes");
311 addPass(PeepholeOptimizerID);
312 printAndVerify("After codegen peephole optimization pass");
315 //===---------------------------------------------------------------------===//
316 /// Register Allocation Pass Configuration
317 //===---------------------------------------------------------------------===//
319 bool TargetPassConfig::getOptimizeRegAlloc() const {
320 switch (OptimizeRegAlloc) {
321 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None;
322 case cl::BOU_TRUE: return true;
323 case cl::BOU_FALSE: return false;
325 llvm_unreachable("Invalid optimize-regalloc state");
328 /// RegisterRegAlloc's global Registry tracks allocator registration.
329 MachinePassRegistry RegisterRegAlloc::Registry;
331 /// A dummy default pass factory indicates whether the register allocator is
332 /// overridden on the command line.
333 static FunctionPass *useDefaultRegisterAllocator() { return 0; }
334 static RegisterRegAlloc
335 defaultRegAlloc("default",
336 "pick register allocator based on -O option",
337 useDefaultRegisterAllocator);
339 /// -regalloc=... command line option.
340 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
341 RegisterPassParser<RegisterRegAlloc> >
343 cl::init(&useDefaultRegisterAllocator),
344 cl::desc("Register allocator to use"));
347 /// Instantiate the default register allocator pass for this target for either
348 /// the optimized or unoptimized allocation path. This will be added to the pass
349 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc
350 /// in the optimized case.
352 /// A target that uses the standard regalloc pass order for fast or optimized
353 /// allocation may still override this for per-target regalloc
354 /// selection. But -regalloc=... always takes precedence.
355 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) {
357 return createGreedyRegisterAllocator();
359 return createFastRegisterAllocator();
362 /// Find and instantiate the register allocation pass requested by this target
363 /// at the current optimization level. Different register allocators are
364 /// defined as separate passes because they may require different analysis.
366 /// This helper ensures that the regalloc= option is always available,
367 /// even for targets that override the default allocator.
369 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs,
370 /// this can be folded into addPass.
371 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) {
372 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
374 // Initialize the global default.
377 RegisterRegAlloc::setDefault(RegAlloc);
379 if (Ctor != useDefaultRegisterAllocator)
382 // With no -regalloc= override, ask the target for a regalloc pass.
383 return createTargetRegisterAllocator(Optimized);
386 /// Add the minimum set of target-independent passes that are required for
387 /// register allocation. No coalescing or scheduling.
388 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) {
389 addPass(PHIEliminationID);
390 addPass(TwoAddressInstructionPassID);
392 PM.add(RegAllocPass);
393 printAndVerify("After Register Allocation");
396 /// Add standard target-independent passes that are tightly coupled with
397 /// optimized register allocation, including coalescing, machine instruction
398 /// scheduling, and register allocation itself.
399 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) {
400 // LiveVariables currently requires pure SSA form.
402 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags,
403 // LiveVariables can be removed completely, and LiveIntervals can be directly
404 // computed. (We still either need to regenerate kill flags after regalloc, or
405 // preferably fix the scavenger to not depend on them).
406 addPass(LiveVariablesID);
408 // Add passes that move from transformed SSA into conventional SSA. This is a
409 // "copy coalescing" problem.
411 if (!EnableStrongPHIElim) {
412 // Edge splitting is smarter with machine loop info.
413 addPass(MachineLoopInfoID);
414 addPass(PHIEliminationID);
416 addPass(TwoAddressInstructionPassID);
418 // FIXME: Either remove this pass completely, or fix it so that it works on
419 // SSA form. We could modify LiveIntervals to be independent of this pass, But
420 // it would be even better to simply eliminate *all* IMPLICIT_DEFs before
422 addPass(ProcessImplicitDefsID);
424 if (EnableStrongPHIElim)
425 addPass(StrongPHIEliminationID);
427 addPass(RegisterCoalescerID);
429 // PreRA instruction scheduling.
430 if (EnableMachineSched)
431 addPass(MachineSchedulerID);
433 // Add the selected register allocation pass.
434 PM.add(RegAllocPass);
435 printAndVerify("After Register Allocation");
437 // Perform stack slot coloring and post-ra machine LICM.
439 // FIXME: Re-enable coloring with register when it's capable of adding
442 addPass(StackSlotColoringID);
444 // Run post-ra machine LICM to hoist reloads / remats.
446 // FIXME: can this move into MachineLateOptimization?
447 if (!DisablePostRAMachineLICM)
448 addPass(MachineLICMID);
450 printAndVerify("After StackSlotColoring and postra Machine LICM");
453 //===---------------------------------------------------------------------===//
454 /// Post RegAlloc Pass Configuration
455 //===---------------------------------------------------------------------===//
457 /// Add passes that optimize machine instructions after register allocation.
458 void TargetPassConfig::addMachineLateOptimization() {
459 // Branch folding must be run after regalloc and prolog/epilog insertion.
460 if (!DisableBranchFold) {
461 addPass(BranchFolderPassID);
462 printNoVerify("After BranchFolding");
466 if (!DisableTailDuplicate) {
467 addPass(TailDuplicateID);
468 printNoVerify("After TailDuplicate");
472 if (!DisableCopyProp) {
473 addPass(MachineCopyPropagationID);
474 printNoVerify("After copy propagation pass");
478 /// Add standard basic block placement passes.
479 void TargetPassConfig::addBlockPlacement() {
480 if (EnableBlockPlacement) {
481 // MachineBlockPlacement is an experimental pass which is disabled by
482 // default currently. Eventually it should subsume CodePlacementOpt, so
483 // when enabled, the other is disabled.
484 addPass(MachineBlockPlacementID);
485 printNoVerify("After MachineBlockPlacement");
487 addPass(CodePlacementOptID);
488 printNoVerify("After CodePlacementOpt");
491 // Run a separate pass to collect block placement statistics.
492 if (EnableBlockPlacementStats) {
493 addPass(MachineBlockPlacementStatsID);
494 printNoVerify("After MachineBlockPlacementStats");