Factor out more code into addCommonCodeGenPasses. The JIT wasn't
[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/FormattedStream.h"
28 using namespace llvm;
29
30 namespace llvm {
31   bool EnableFastISel;
32 }
33
34 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
35     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
36 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
37     cl::desc("Print LLVM IR input to isel pass"));
38 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
39     cl::desc("Dump emitter generated instructions as assembly"));
40 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
41     cl::desc("Dump garbage collector data"));
42 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
43     cl::desc("Verify generated machine code"),
44     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
45
46 // Enable or disable FastISel. Both options are needed, because
47 // FastISel is enabled by default with -fast, and we wish to be
48 // able to enable or disable fast-isel independently from -O0.
49 static cl::opt<cl::boolOrDefault>
50 EnableFastISelOption("fast-isel", cl::Hidden,
51   cl::desc("Enable the \"fast\" instruction selector"));
52
53
54 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
55                                      const std::string &TargetTriple)
56   : TargetMachine(T) {
57   AsmInfo = T.createAsmInfo(TargetTriple);
58 }
59
60
61
62 FileModel::Model
63 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
64                                        formatted_raw_ostream &Out,
65                                        CodeGenFileType FileType,
66                                        CodeGenOpt::Level OptLevel) {
67   // Add common CodeGen passes.
68   if (addCommonCodeGenPasses(PM, OptLevel))
69     return FileModel::Error;
70
71   switch (FileType) {
72   default:
73     break;
74   case TargetMachine::AssemblyFile:
75     if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
76       return FileModel::Error;
77     return FileModel::AsmFile;
78   case TargetMachine::ObjectFile:
79     if (getMachOWriterInfo())
80       return FileModel::MachOFile;
81     else if (getELFWriterInfo())
82       return FileModel::ElfFile;
83   }
84
85   return FileModel::Error;
86 }
87
88 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
89                                            CodeGenOpt::Level OptLevel,
90                                            bool Verbose,
91                                            formatted_raw_ostream &Out) {
92   FunctionPass *Printer =
93     getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
94   if (!Printer)
95     return true;
96
97   PM.add(Printer);
98   return false;
99 }
100
101 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
102 /// be split up (e.g., to add an object writer pass), this method can be used to
103 /// finish up adding passes to emit the file, if necessary.
104 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
105                                                   MachineCodeEmitter *MCE,
106                                                   CodeGenOpt::Level OptLevel) {
107   if (MCE)
108     addSimpleCodeEmitter(PM, OptLevel, *MCE);
109   if (PrintEmittedAsm)
110     addAssemblyEmitter(PM, OptLevel, true, ferrs());
111
112   PM.add(createGCInfoDeleter());
113
114   return false; // success!
115 }
116
117 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
118 /// be split up (e.g., to add an object writer pass), this method can be used to
119 /// finish up adding passes to emit the file, if necessary.
120 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
121                                                   JITCodeEmitter *JCE,
122                                                   CodeGenOpt::Level OptLevel) {
123   if (JCE)
124     addSimpleCodeEmitter(PM, OptLevel, *JCE);
125   if (PrintEmittedAsm)
126     addAssemblyEmitter(PM, OptLevel, true, ferrs());
127
128   PM.add(createGCInfoDeleter());
129
130   return false; // success!
131 }
132
133 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
134 /// be split up (e.g., to add an object writer pass), this method can be used to
135 /// finish up adding passes to emit the file, if necessary.
136 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
137                                                   ObjectCodeEmitter *OCE,
138                                                   CodeGenOpt::Level OptLevel) {
139   if (OCE)
140     addSimpleCodeEmitter(PM, OptLevel, *OCE);
141   if (PrintEmittedAsm)
142     addAssemblyEmitter(PM, OptLevel, true, ferrs());
143
144   PM.add(createGCInfoDeleter());
145
146   return false; // success!
147 }
148
149 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
150 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
151 /// actually outputting the machine code and resolving things like the address
152 /// of functions.  This method should returns true if machine code emission is
153 /// not supported.
154 ///
155 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
156                                                    MachineCodeEmitter &MCE,
157                                                    CodeGenOpt::Level OptLevel) {
158   // Add common CodeGen passes.
159   if (addCommonCodeGenPasses(PM, OptLevel))
160     return true;
161
162   addCodeEmitter(PM, OptLevel, MCE);
163   if (PrintEmittedAsm)
164     addAssemblyEmitter(PM, OptLevel, true, ferrs());
165
166   PM.add(createGCInfoDeleter());
167
168   return false; // success!
169 }
170
171 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
172 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
173 /// actually outputting the machine code and resolving things like the address
174 /// of functions.  This method should returns true if machine code emission is
175 /// not supported.
176 ///
177 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
178                                                    JITCodeEmitter &JCE,
179                                                    CodeGenOpt::Level OptLevel) {
180   // Add common CodeGen passes.
181   if (addCommonCodeGenPasses(PM, OptLevel))
182     return true;
183
184   addCodeEmitter(PM, OptLevel, JCE);
185   if (PrintEmittedAsm)
186     addAssemblyEmitter(PM, OptLevel, true, ferrs());
187
188   PM.add(createGCInfoDeleter());
189
190   return false; // success!
191 }
192
193 static void printAndVerify(PassManagerBase &PM,
194                            const char *Banner,
195                            bool allowDoubleDefs = false) {
196   if (PrintMachineCode)
197     PM.add(createMachineFunctionPrinterPass(errs(), Banner));
198
199   if (VerifyMachineCode)
200     PM.add(createMachineVerifierPass(allowDoubleDefs));
201 }
202
203 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
204 /// emitting to assembly files or machine code output.
205 ///
206 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
207                                                CodeGenOpt::Level OptLevel) {
208   // Standard LLVM-Level Passes.
209
210   // Run loop strength reduction before anything else.
211   if (OptLevel != CodeGenOpt::None) {
212     PM.add(createLoopStrengthReducePass(getTargetLowering()));
213     if (PrintLSR)
214       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
215   }
216
217   // Turn exception handling constructs into something the code generators can
218   // handle.
219   switch (getMCAsmInfo()->getExceptionHandlingType())
220   {
221   case ExceptionHandling::SjLj:
222     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
223     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
224     PM.add(createSjLjEHPass(getTargetLowering()));
225     break;
226   case ExceptionHandling::Dwarf:
227     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
228     break;
229   case ExceptionHandling::None:
230     PM.add(createLowerInvokePass(getTargetLowering()));
231     break;
232   }
233
234   PM.add(createGCLoweringPass());
235
236   // Make sure that no unreachable blocks are instruction selected.
237   PM.add(createUnreachableBlockEliminationPass());
238
239   if (OptLevel != CodeGenOpt::None)
240     PM.add(createCodeGenPreparePass(getTargetLowering()));
241
242   PM.add(createStackProtectorPass(getTargetLowering()));
243
244   if (PrintISelInput)
245     PM.add(createPrintFunctionPass("\n\n"
246                                    "*** Final LLVM Code input to ISel ***\n",
247                                    &errs()));
248
249   // Standard Lower-Level Passes.
250
251   // Set up a MachineFunction for the rest of CodeGen to work on.
252   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
253
254   // Enable FastISel with -fast, but allow that to be overridden.
255   if (EnableFastISelOption == cl::BOU_TRUE ||
256       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
257     EnableFastISel = true;
258
259   // Ask the target for an isel.
260   if (addInstSelector(PM, OptLevel))
261     return true;
262
263   // Print the instruction selected machine code...
264   printAndVerify(PM, "After Instruction Selection",
265                  /* allowDoubleDefs= */ true);
266
267   if (OptLevel != CodeGenOpt::None) {
268     PM.add(createMachineLICMPass());
269     PM.add(createMachineSinkingPass());
270     printAndVerify(PM, "After MachineLICM and MachineSinking",
271                    /* allowDoubleDefs= */ true);
272   }
273
274   // Run pre-ra passes.
275   if (addPreRegAlloc(PM, OptLevel))
276     printAndVerify(PM, "After PreRegAlloc passes",
277                    /* allowDoubleDefs= */ true);
278
279   // Perform register allocation.
280   PM.add(createRegisterAllocator());
281   printAndVerify(PM, "After Register Allocation");
282
283   // Perform stack slot coloring.
284   if (OptLevel != CodeGenOpt::None) {
285     // FIXME: Re-enable coloring with register when it's capable of adding
286     // kill markers.
287     PM.add(createStackSlotColoringPass(false));
288     printAndVerify(PM, "After StackSlotColoring");
289   }
290
291   // Run post-ra passes.
292   if (addPostRegAlloc(PM, OptLevel))
293     printAndVerify(PM, "After PostRegAlloc passes");
294
295   PM.add(createLowerSubregsPass());
296   printAndVerify(PM, "After LowerSubregs");
297
298   // Insert prolog/epilog code.  Eliminate abstract frame index references...
299   PM.add(createPrologEpilogCodeInserter());
300   printAndVerify(PM, "After PrologEpilogCodeInserter");
301
302   // Run pre-sched2 passes.
303   if (addPreSched2(PM, OptLevel))
304     printAndVerify(PM, "After PreSched2 passes");
305
306   // Second pass scheduler.
307   if (OptLevel != CodeGenOpt::None) {
308     PM.add(createPostRAScheduler(OptLevel));
309     printAndVerify(PM, "After PostRAScheduler");
310   }
311
312   // Branch folding must be run after regalloc and prolog/epilog insertion.
313   if (OptLevel != CodeGenOpt::None) {
314     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
315     printAndVerify(PM, "After BranchFolding");
316   }
317
318   PM.add(createGCMachineCodeAnalysisPass());
319
320   if (PrintGCInfo)
321     PM.add(createGCInfoPrinter(errs()));
322
323   // Fold redundant debug labels.
324   PM.add(createDebugLabelFoldingPass());
325   printAndVerify(PM, "After DebugLabelFolding");
326
327   if (addPreEmitPass(PM, OptLevel))
328     printAndVerify(PM, "After PreEmit passes");
329
330   if (OptLevel != CodeGenOpt::None) {
331     PM.add(createCodePlacementOptPass());
332     printAndVerify(PM, "After CodePlacementOpt");
333   }
334
335   return false;
336 }