Remove a bunch of stuff around the edges of the ELF writer.
[oota-llvm.git] / lib / CodeGen / LLVMTargetMachine.cpp
1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
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 implements the LLVMTargetMachine class.
11 //
12 //===----------------------------------------------------------------------===//
13
14 #include "llvm/Target/TargetMachine.h"
15 #include "llvm/PassManager.h"
16 #include "llvm/Pass.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/Passes.h"
20 #include "llvm/CodeGen/GCStrategy.h"
21 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
22 #include "llvm/Target/TargetOptions.h"
23 #include "llvm/MC/MCAsmInfo.h"
24 #include "llvm/Target/TargetRegistry.h"
25 #include "llvm/Transforms/Scalar.h"
26 #include "llvm/Support/CommandLine.h"
27 #include "llvm/Support/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
29 using namespace llvm;
30
31 namespace llvm {
32   bool EnableFastISel;
33 }
34
35 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
36     cl::desc("Disable Post Regalloc"));
37 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
38     cl::desc("Disable branch folding"));
39 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
40     cl::desc("Disable tail duplication"));
41 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
42     cl::desc("Disable pre-register allocation tail duplication"));
43 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
44     cl::desc("Disable code placement"));
45 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
46     cl::desc("Disable Stack Slot Coloring"));
47 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
48     cl::desc("Disable Machine LICM"));
49 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
50     cl::desc("Disable Machine Sinking"));
51 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
52     cl::desc("Disable Loop Strength Reduction Pass"));
53 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
54     cl::desc("Disable Codegen Prepare"));
55 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
56     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
57 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
58     cl::desc("Print LLVM IR input to isel pass"));
59 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
60     cl::desc("Dump garbage collector data"));
61 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
62     cl::desc("Verify generated machine code"),
63     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
64
65
66 // Enable or disable FastISel. Both options are needed, because
67 // FastISel is enabled by default with -fast, and we wish to be
68 // able to enable or disable fast-isel independently from -O0.
69 static cl::opt<cl::boolOrDefault>
70 EnableFastISelOption("fast-isel", cl::Hidden,
71   cl::desc("Enable the \"fast\" instruction selector"));
72
73 // Enable or disable an experimental optimization to split GEPs
74 // and run a special GVN pass which does not examine loads, in
75 // an effort to factor out redundancy implicit in complex GEPs.
76 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
77     cl::desc("Split GEPs and run no-load GVN"));
78
79 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
80                                      const std::string &TargetTriple)
81   : TargetMachine(T) {
82   AsmInfo = T.createAsmInfo(TargetTriple);
83 }
84
85 // Set the default code model for the JIT for a generic target.
86 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
87 void
88 LLVMTargetMachine::setCodeModelForJIT() {
89   setCodeModel(CodeModel::Small);
90 }
91
92 // Set the default code model for static compilation for a generic target.
93 void
94 LLVMTargetMachine::setCodeModelForStatic() {
95   setCodeModel(CodeModel::Small);
96 }
97
98 TargetMachine::CodeGenFileType
99 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
100                                        formatted_raw_ostream &Out,
101                                        CodeGenFileType FileType,
102                                        CodeGenOpt::Level OptLevel) {
103   // Add common CodeGen passes.
104   if (addCommonCodeGenPasses(PM, OptLevel))
105     return CGFT_ErrorOccurred;
106
107   switch (FileType) {
108   default:
109   case CGFT_ObjectFile:
110     return CGFT_ErrorOccurred;
111   case CGFT_AssemblyFile: {
112     FunctionPass *Printer =
113       getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(),
114                                    getAsmVerbosityDefault());
115     if (Printer == 0) return CGFT_ErrorOccurred;
116     PM.add(Printer);
117     break;
118   }
119   }
120   
121   // Make sure the code model is set.
122   setCodeModelForStatic();
123   PM.add(createGCInfoDeleter());
124   return FileType;
125 }
126
127 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
128 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
129 /// actually outputting the machine code and resolving things like the address
130 /// of functions.  This method should returns true if machine code emission is
131 /// not supported.
132 ///
133 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
134                                                    JITCodeEmitter &JCE,
135                                                    CodeGenOpt::Level OptLevel) {
136   // Make sure the code model is set.
137   setCodeModelForJIT();
138   
139   // Add common CodeGen passes.
140   if (addCommonCodeGenPasses(PM, OptLevel))
141     return true;
142
143   addCodeEmitter(PM, OptLevel, JCE);
144   PM.add(createGCInfoDeleter());
145
146   return false; // success!
147 }
148
149 static void printAndVerify(PassManagerBase &PM,
150                            const char *Banner,
151                            bool allowDoubleDefs = false) {
152   if (PrintMachineCode)
153     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
154
155   if (VerifyMachineCode)
156     PM.add(createMachineVerifierPass(allowDoubleDefs));
157 }
158
159 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
160 /// emitting to assembly files or machine code output.
161 ///
162 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
163                                                CodeGenOpt::Level OptLevel) {
164   // Standard LLVM-Level Passes.
165
166   // Optionally, tun split-GEPs and no-load GVN.
167   if (EnableSplitGEPGVN) {
168     PM.add(createGEPSplitterPass());
169     PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
170   }
171
172   // Run loop strength reduction before anything else.
173   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
174     PM.add(createLoopStrengthReducePass(getTargetLowering()));
175     if (PrintLSR)
176       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
177   }
178
179   // Turn exception handling constructs into something the code generators can
180   // handle.
181   switch (getMCAsmInfo()->getExceptionHandlingType())
182   {
183   case ExceptionHandling::SjLj:
184     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
185     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
186     // catch info can get misplaced when a selector ends up more than one block
187     // removed from the parent invoke(s). This could happen when a landing
188     // pad is shared by multiple invokes and is also a target of a normal
189     // edge from elsewhere.
190     PM.add(createSjLjEHPass(getTargetLowering()));
191     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
192     break;
193   case ExceptionHandling::Dwarf:
194     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
195     break;
196   case ExceptionHandling::None:
197     PM.add(createLowerInvokePass(getTargetLowering()));
198     break;
199   }
200
201   PM.add(createGCLoweringPass());
202
203   // Make sure that no unreachable blocks are instruction selected.
204   PM.add(createUnreachableBlockEliminationPass());
205
206   if (OptLevel != CodeGenOpt::None && !DisableCGP)
207     PM.add(createCodeGenPreparePass(getTargetLowering()));
208
209   PM.add(createStackProtectorPass(getTargetLowering()));
210
211   if (PrintISelInput)
212     PM.add(createPrintFunctionPass("\n\n"
213                                    "*** Final LLVM Code input to ISel ***\n",
214                                    &dbgs()));
215
216   // Standard Lower-Level Passes.
217
218   // Set up a MachineFunction for the rest of CodeGen to work on.
219   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
220
221   // Enable FastISel with -fast, but allow that to be overridden.
222   if (EnableFastISelOption == cl::BOU_TRUE ||
223       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
224     EnableFastISel = true;
225
226   // Ask the target for an isel.
227   if (addInstSelector(PM, OptLevel))
228     return true;
229
230   // Print the instruction selected machine code...
231   printAndVerify(PM, "After Instruction Selection",
232                  /* allowDoubleDefs= */ true);
233
234   if (OptLevel != CodeGenOpt::None) {
235     PM.add(createOptimizeExtsPass());
236     if (!DisableMachineLICM)
237       PM.add(createMachineLICMPass());
238     if (!DisableMachineSink)
239       PM.add(createMachineSinkingPass());
240     printAndVerify(PM, "After MachineLICM and MachineSinking",
241                    /* allowDoubleDefs= */ true);
242   }
243
244   // Pre-ra tail duplication.
245   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
246     PM.add(createTailDuplicatePass(true));
247     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
248                    /* allowDoubleDefs= */ true);
249   }
250
251   // Run pre-ra passes.
252   if (addPreRegAlloc(PM, OptLevel))
253     printAndVerify(PM, "After PreRegAlloc passes",
254                    /* allowDoubleDefs= */ true);
255
256   // Perform register allocation.
257   PM.add(createRegisterAllocator());
258   printAndVerify(PM, "After Register Allocation");
259
260   // Perform stack slot coloring.
261   if (OptLevel != CodeGenOpt::None && !DisableSSC) {
262     // FIXME: Re-enable coloring with register when it's capable of adding
263     // kill markers.
264     PM.add(createStackSlotColoringPass(false));
265     printAndVerify(PM, "After StackSlotColoring");
266   }
267
268   // Run post-ra passes.
269   if (addPostRegAlloc(PM, OptLevel))
270     printAndVerify(PM, "After PostRegAlloc passes");
271
272   PM.add(createLowerSubregsPass());
273   printAndVerify(PM, "After LowerSubregs");
274
275   // Insert prolog/epilog code.  Eliminate abstract frame index references...
276   PM.add(createPrologEpilogCodeInserter());
277   printAndVerify(PM, "After PrologEpilogCodeInserter");
278
279   // Run pre-sched2 passes.
280   if (addPreSched2(PM, OptLevel))
281     printAndVerify(PM, "After PreSched2 passes");
282
283   // Second pass scheduler.
284   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
285     PM.add(createPostRAScheduler(OptLevel));
286     printAndVerify(PM, "After PostRAScheduler");
287   }
288
289   // Branch folding must be run after regalloc and prolog/epilog insertion.
290   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
291     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
292     printAndVerify(PM, "After BranchFolding");
293   }
294
295   // Tail duplication.
296   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
297     PM.add(createTailDuplicatePass(false));
298     printAndVerify(PM, "After TailDuplicate");
299   }
300
301   PM.add(createGCMachineCodeAnalysisPass());
302
303   if (PrintGCInfo)
304     PM.add(createGCInfoPrinter(dbgs()));
305
306   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
307     PM.add(createCodePlacementOptPass());
308     printAndVerify(PM, "After CodePlacementOpt");
309   }
310
311   if (addPreEmitPass(PM, OptLevel))
312     printAndVerify(PM, "After PreEmit passes");
313
314   return false;
315 }