TargetPassConfig: confine the MC configuration to TargetMachine.
[oota-llvm.git] / lib / CodeGen / Passes.cpp
1 //===-- Passes.cpp - Target independent code generation passes ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file defines interfaces to access the target independent code
11 // generation passes provided by the LLVM backend.
12 //
13 //===---------------------------------------------------------------------===//
14
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"
29
30 using namespace llvm;
31
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<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
55     cl::Hidden,
56     cl::desc("Disable Machine LICM"));
57 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
58     cl::desc("Disable Machine Sinking"));
59 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
60     cl::desc("Disable Loop Strength Reduction Pass"));
61 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
62     cl::desc("Disable Codegen Prepare"));
63 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden,
64     cl::desc("Disable Copy Propagation pass"));
65 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
66     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
67 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
68     cl::desc("Print LLVM IR input to isel pass"));
69 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
70     cl::desc("Dump garbage collector data"));
71 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
72     cl::desc("Verify generated machine code"),
73     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
74
75 //===---------------------------------------------------------------------===//
76 /// TargetPassConfig
77 //===---------------------------------------------------------------------===//
78
79 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig",
80                 "Target Pass Configuration", false, false)
81 char TargetPassConfig::ID = 0;
82
83 // Out of line virtual method.
84 TargetPassConfig::~TargetPassConfig() {}
85
86 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm)
87   : ImmutablePass(ID), TM(tm), PM(pm), DisableVerify(false) {
88   // Register all target independent codegen passes to activate their PassIDs,
89   // including this pass itself.
90   initializeCodeGen(*PassRegistry::getPassRegistry());
91 }
92
93 /// createPassConfig - Create a pass configuration object to be used by
94 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
95 ///
96 /// Targets may override this to extend TargetPassConfig.
97 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) {
98   return new TargetPassConfig(this, PM);
99 }
100
101 TargetPassConfig::TargetPassConfig()
102   : ImmutablePass(ID), PM(*(PassManagerBase*)0) {
103   llvm_unreachable("TargetPassConfig should not be constructed on-the-fly");
104 }
105
106 void TargetPassConfig::addCommonPass(char &ID) {
107   // FIXME: about to be implemented.
108 }
109
110 void TargetPassConfig::printNoVerify(const char *Banner) const {
111   if (TM->shouldPrintMachineCode())
112     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
113 }
114
115 void TargetPassConfig::printAndVerify(const char *Banner) const {
116   if (TM->shouldPrintMachineCode())
117     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
118
119   if (VerifyMachineCode)
120     PM.add(createMachineVerifierPass(Banner));
121 }
122
123 /// Add common target configurable passes that perform LLVM IR to IR transforms
124 /// following machine independent optimization.
125 void TargetPassConfig::addIRPasses() {
126   // Basic AliasAnalysis support.
127   // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
128   // BasicAliasAnalysis wins if they disagree. This is intended to help
129   // support "obvious" type-punning idioms.
130   PM.add(createTypeBasedAliasAnalysisPass());
131   PM.add(createBasicAliasAnalysisPass());
132
133   // Before running any passes, run the verifier to determine if the input
134   // coming from the front-end and/or optimizer is valid.
135   if (!DisableVerify)
136     PM.add(createVerifierPass());
137
138   // Run loop strength reduction before anything else.
139   if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
140     PM.add(createLoopStrengthReducePass(getTargetLowering()));
141     if (PrintLSR)
142       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
143   }
144
145   PM.add(createGCLoweringPass());
146
147   // Make sure that no unreachable blocks are instruction selected.
148   PM.add(createUnreachableBlockEliminationPass());
149 }
150
151 /// Add common passes that perform LLVM IR to IR transforms in preparation for
152 /// instruction selection.
153 void TargetPassConfig::addISelPrepare() {
154   if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
155     PM.add(createCodeGenPreparePass(getTargetLowering()));
156
157   PM.add(createStackProtectorPass(getTargetLowering()));
158
159   addPreISel();
160
161   if (PrintISelInput)
162     PM.add(createPrintFunctionPass("\n\n"
163                                    "*** Final LLVM Code input to ISel ***\n",
164                                    &dbgs()));
165
166   // All passes which modify the LLVM IR are now complete; run the verifier
167   // to ensure that the IR is valid.
168   if (!DisableVerify)
169     PM.add(createVerifierPass());
170 }
171
172 void TargetPassConfig::addMachinePasses() {
173   // Print the instruction selected machine code...
174   printAndVerify("After Instruction Selection");
175
176   // Expand pseudo-instructions emitted by ISel.
177   PM.add(createExpandISelPseudosPass());
178
179   // Pre-ra tail duplication.
180   if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
181     PM.add(createTailDuplicatePass(true));
182     printAndVerify("After Pre-RegAlloc TailDuplicate");
183   }
184
185   // Optimize PHIs before DCE: removing dead PHI cycles may make more
186   // instructions dead.
187   if (getOptLevel() != CodeGenOpt::None)
188     PM.add(createOptimizePHIsPass());
189
190   // If the target requests it, assign local variables to stack slots relative
191   // to one another and simplify frame index references where possible.
192   PM.add(createLocalStackSlotAllocationPass());
193
194   if (getOptLevel() != CodeGenOpt::None) {
195     // With optimization, dead code should already be eliminated. However
196     // there is one known exception: lowered code for arguments that are only
197     // used by tail calls, where the tail calls reuse the incoming stack
198     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
199     if (!DisableMachineDCE)
200       PM.add(createDeadMachineInstructionElimPass());
201     printAndVerify("After codegen DCE pass");
202
203     if (!DisableMachineLICM)
204       PM.add(createMachineLICMPass());
205     if (!DisableMachineCSE)
206       PM.add(createMachineCSEPass());
207     if (!DisableMachineSink)
208       PM.add(createMachineSinkingPass());
209     printAndVerify("After Machine LICM, CSE and Sinking passes");
210
211     PM.add(createPeepholeOptimizerPass());
212     printAndVerify("After codegen peephole optimization pass");
213   }
214
215   // Run pre-ra passes.
216   if (addPreRegAlloc())
217     printAndVerify("After PreRegAlloc passes");
218
219   // Perform register allocation.
220   PM.add(createRegisterAllocator(getOptLevel()));
221   printAndVerify("After Register Allocation");
222
223   // Perform stack slot coloring and post-ra machine LICM.
224   if (getOptLevel() != CodeGenOpt::None) {
225     // FIXME: Re-enable coloring with register when it's capable of adding
226     // kill markers.
227     if (!DisableSSC)
228       PM.add(createStackSlotColoringPass(false));
229
230     // Run post-ra machine LICM to hoist reloads / remats.
231     if (!DisablePostRAMachineLICM)
232       PM.add(createMachineLICMPass(false));
233
234     printAndVerify("After StackSlotColoring and postra Machine LICM");
235   }
236
237   // Run post-ra passes.
238   if (addPostRegAlloc())
239     printAndVerify("After PostRegAlloc passes");
240
241   // Insert prolog/epilog code.  Eliminate abstract frame index references...
242   PM.add(createPrologEpilogCodeInserter());
243   printAndVerify("After PrologEpilogCodeInserter");
244
245   // Branch folding must be run after regalloc and prolog/epilog insertion.
246   if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
247     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
248     printNoVerify("After BranchFolding");
249   }
250
251   // Tail duplication.
252   if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
253     PM.add(createTailDuplicatePass(false));
254     printNoVerify("After TailDuplicate");
255   }
256
257   // Copy propagation.
258   if (getOptLevel() != CodeGenOpt::None && !DisableCopyProp) {
259     PM.add(createMachineCopyPropagationPass());
260     printNoVerify("After copy propagation pass");
261   }
262
263   // Expand pseudo instructions before second scheduling pass.
264   PM.add(createExpandPostRAPseudosPass());
265   printNoVerify("After ExpandPostRAPseudos");
266
267   // Run pre-sched2 passes.
268   if (addPreSched2())
269     printNoVerify("After PreSched2 passes");
270
271   // Second pass scheduler.
272   if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
273     PM.add(createPostRAScheduler(getOptLevel()));
274     printNoVerify("After PostRAScheduler");
275   }
276
277   PM.add(createGCMachineCodeAnalysisPass());
278
279   if (PrintGCInfo)
280     PM.add(createGCInfoPrinter(dbgs()));
281
282   if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
283     if (EnableBlockPlacement) {
284       // MachineBlockPlacement is an experimental pass which is disabled by
285       // default currently. Eventually it should subsume CodePlacementOpt, so
286       // when enabled, the other is disabled.
287       PM.add(createMachineBlockPlacementPass());
288       printNoVerify("After MachineBlockPlacement");
289     } else {
290       PM.add(createCodePlacementOptPass());
291       printNoVerify("After CodePlacementOpt");
292     }
293
294     // Run a separate pass to collect block placement statistics.
295     if (EnableBlockPlacementStats) {
296       PM.add(createMachineBlockPlacementStatsPass());
297       printNoVerify("After MachineBlockPlacementStats");
298     }
299   }
300
301   if (addPreEmitPass())
302     printNoVerify("After PreEmit passes");
303 }
304
305 //===---------------------------------------------------------------------===//
306 ///
307 /// RegisterRegAlloc class - Track the registration of register allocators.
308 ///
309 //===---------------------------------------------------------------------===//
310 MachinePassRegistry RegisterRegAlloc::Registry;
311
312 static FunctionPass *createDefaultRegisterAllocator() { return 0; }
313 static RegisterRegAlloc
314 defaultRegAlloc("default",
315                 "pick register allocator based on -O option",
316                 createDefaultRegisterAllocator);
317
318 //===---------------------------------------------------------------------===//
319 ///
320 /// RegAlloc command line options.
321 ///
322 //===---------------------------------------------------------------------===//
323 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false,
324                RegisterPassParser<RegisterRegAlloc> >
325 RegAlloc("regalloc",
326          cl::init(&createDefaultRegisterAllocator),
327          cl::desc("Register allocator to use"));
328
329
330 //===---------------------------------------------------------------------===//
331 ///
332 /// createRegisterAllocator - choose the appropriate register allocator.
333 ///
334 //===---------------------------------------------------------------------===//
335 FunctionPass *llvm::createRegisterAllocator(CodeGenOpt::Level OptLevel) {
336   RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault();
337
338   if (!Ctor) {
339     Ctor = RegAlloc;
340     RegisterRegAlloc::setDefault(RegAlloc);
341   }
342
343   if (Ctor != createDefaultRegisterAllocator)
344     return Ctor();
345
346   // When the 'default' allocator is requested, pick one based on OptLevel.
347   switch (OptLevel) {
348   case CodeGenOpt::None:
349     return createFastRegisterAllocator();
350   default:
351     return createGreedyRegisterAllocator();
352   }
353 }