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