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