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