Add X86 instruction printer support for printing MCValue operands.
[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/Target/TargetAsmInfo.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, getTargetAsmInfo(), 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 (getTargetAsmInfo()->getExceptionHandlingType())
243   {
244   // SjLj piggy-backs on dwarf for this bit
245   case ExceptionHandling::SjLj:
246   case ExceptionHandling::Dwarf:
247     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
248     break;
249   case ExceptionHandling::None:
250     PM.add(createLowerInvokePass(getTargetLowering()));
251     break;
252   }
253
254   PM.add(createGCLoweringPass());
255
256   // Make sure that no unreachable blocks are instruction selected.
257   PM.add(createUnreachableBlockEliminationPass());
258
259   if (OptLevel != CodeGenOpt::None)
260     PM.add(createCodeGenPreparePass(getTargetLowering()));
261
262   PM.add(createStackProtectorPass(getTargetLowering()));
263
264   if (PrintISelInput)
265     PM.add(createPrintFunctionPass("\n\n"
266                                    "*** Final LLVM Code input to ISel ***\n",
267                                    &errs()));
268
269   // Standard Lower-Level Passes.
270
271   // Set up a MachineFunction for the rest of CodeGen to work on.
272   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
273
274   // Enable FastISel with -fast, but allow that to be overridden.
275   if (EnableFastISelOption == cl::BOU_TRUE ||
276       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
277     EnableFastISel = true;
278
279   // Ask the target for an isel.
280   if (addInstSelector(PM, OptLevel))
281     return true;
282
283   // Print the instruction selected machine code...
284   printAndVerify(PM, /* allowDoubleDefs= */ true);
285
286   if (OptLevel != CodeGenOpt::None) {
287     PM.add(createMachineLICMPass());
288     PM.add(createMachineSinkingPass());
289     printAndVerify(PM, /* allowDoubleDefs= */ true);
290   }
291
292   // Run pre-ra passes.
293   if (addPreRegAlloc(PM, OptLevel))
294     printAndVerify(PM);
295
296   // Perform register allocation.
297   PM.add(createRegisterAllocator());
298
299   // Perform stack slot coloring.
300   if (OptLevel != CodeGenOpt::None)
301     // FIXME: Re-enable coloring with register when it's capable of adding
302     // kill markers.
303     PM.add(createStackSlotColoringPass(false));
304
305   printAndVerify(PM);           // Print the register-allocated code
306
307   // Run post-ra passes.
308   if (addPostRegAlloc(PM, OptLevel))
309     printAndVerify(PM);
310
311   PM.add(createLowerSubregsPass());
312   printAndVerify(PM);
313
314   // Insert prolog/epilog code.  Eliminate abstract frame index references...
315   PM.add(createPrologEpilogCodeInserter());
316   printAndVerify(PM);
317
318   // Second pass scheduler.
319   if (OptLevel != CodeGenOpt::None && !DisablePostRAScheduler) {
320     PM.add(createPostRAScheduler());
321     printAndVerify(PM);
322   }
323
324   // Branch folding must be run after regalloc and prolog/epilog insertion.
325   if (OptLevel != CodeGenOpt::None) {
326     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
327     printAndVerify(PM);
328   }
329
330   PM.add(createGCMachineCodeAnalysisPass());
331   printAndVerify(PM);
332
333   if (PrintGCInfo)
334     PM.add(createGCInfoPrinter(*cerr));
335
336   return false;
337 }