Fix a typo in a comment.
[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> DisableCodePlace("disable-code-place", cl::Hidden,
42     cl::desc("Disable code placement"));
43 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
44     cl::desc("Disable Stack Slot Coloring"));
45 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
46     cl::desc("Disable Machine LICM"));
47 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
48     cl::desc("Disable Machine Sinking"));
49 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
50     cl::desc("Disable Loop Strength Reduction Pass"));
51 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
52     cl::desc("Disable Codegen Prepare"));
53 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
54     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
55 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
56     cl::desc("Print LLVM IR input to isel pass"));
57 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
58     cl::desc("Dump emitter generated instructions as assembly"));
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 // Enable or disable FastISel. Both options are needed, because
66 // FastISel is enabled by default with -fast, and we wish to be
67 // able to enable or disable fast-isel independently from -O0.
68 static cl::opt<cl::boolOrDefault>
69 EnableFastISelOption("fast-isel", cl::Hidden,
70   cl::desc("Enable the \"fast\" instruction selector"));
71
72 // Enable or disable an experimental optimization to split GEPs
73 // and run a special GVN pass which does not examine loads, in
74 // an effort to factor out redundancy implicit in complex GEPs.
75 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
76     cl::desc("Split GEPs and run no-load GVN"));
77
78 static cl::opt<bool> PreAllocTailDup("pre-regalloc-taildup", cl::Hidden,
79     cl::desc("Pre-register allocation tail duplication"));
80
81 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
82                                      const std::string &TargetTriple)
83   : TargetMachine(T) {
84   AsmInfo = T.createAsmInfo(TargetTriple);
85 }
86
87 // Set the default code model for the JIT for a generic target.
88 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
89 void
90 LLVMTargetMachine::setCodeModelForJIT() {
91   setCodeModel(CodeModel::Small);
92 }
93
94 // Set the default code model for static compilation for a generic target.
95 void
96 LLVMTargetMachine::setCodeModelForStatic() {
97   setCodeModel(CodeModel::Small);
98 }
99
100 FileModel::Model
101 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
102                                        formatted_raw_ostream &Out,
103                                        CodeGenFileType FileType,
104                                        CodeGenOpt::Level OptLevel) {
105   // Add common CodeGen passes.
106   if (addCommonCodeGenPasses(PM, OptLevel))
107     return FileModel::Error;
108
109   switch (FileType) {
110   default:
111     break;
112   case TargetMachine::AssemblyFile:
113     if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
114       return FileModel::Error;
115     return FileModel::AsmFile;
116   case TargetMachine::ObjectFile:
117     if (getMachOWriterInfo())
118       return FileModel::MachOFile;
119     else if (getELFWriterInfo())
120       return FileModel::ElfFile;
121   }
122
123   return FileModel::Error;
124 }
125
126 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
127                                            CodeGenOpt::Level OptLevel,
128                                            bool Verbose,
129                                            formatted_raw_ostream &Out) {
130   FunctionPass *Printer =
131     getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
132   if (!Printer)
133     return true;
134
135   PM.add(Printer);
136   return false;
137 }
138
139 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
140 /// be split up (e.g., to add an object writer pass), this method can be used to
141 /// finish up adding passes to emit the file, if necessary.
142 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
143                                                   MachineCodeEmitter *MCE,
144                                                   CodeGenOpt::Level OptLevel) {
145   // Make sure the code model is set.
146   setCodeModelForStatic();
147   
148   if (MCE)
149     addSimpleCodeEmitter(PM, OptLevel, *MCE);
150   if (PrintEmittedAsm)
151     addAssemblyEmitter(PM, OptLevel, true, ferrs());
152
153   PM.add(createGCInfoDeleter());
154
155   return false; // success!
156 }
157
158 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
159 /// be split up (e.g., to add an object writer pass), this method can be used to
160 /// finish up adding passes to emit the file, if necessary.
161 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
162                                                   JITCodeEmitter *JCE,
163                                                   CodeGenOpt::Level OptLevel) {
164   // Make sure the code model is set.
165   setCodeModelForJIT();
166   
167   if (JCE)
168     addSimpleCodeEmitter(PM, OptLevel, *JCE);
169   if (PrintEmittedAsm)
170     addAssemblyEmitter(PM, OptLevel, true, ferrs());
171
172   PM.add(createGCInfoDeleter());
173
174   return false; // success!
175 }
176
177 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
178 /// be split up (e.g., to add an object writer pass), this method can be used to
179 /// finish up adding passes to emit the file, if necessary.
180 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
181                                                   ObjectCodeEmitter *OCE,
182                                                   CodeGenOpt::Level OptLevel) {
183   // Make sure the code model is set.
184   setCodeModelForStatic();
185   
186   if (OCE)
187     addSimpleCodeEmitter(PM, OptLevel, *OCE);
188   if (PrintEmittedAsm)
189     addAssemblyEmitter(PM, OptLevel, true, ferrs());
190
191   PM.add(createGCInfoDeleter());
192
193   return false; // success!
194 }
195
196 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
197 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
198 /// actually outputting the machine code and resolving things like the address
199 /// of functions.  This method should returns true if machine code emission is
200 /// not supported.
201 ///
202 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
203                                                    MachineCodeEmitter &MCE,
204                                                    CodeGenOpt::Level OptLevel) {
205   // Make sure the code model is set.
206   setCodeModelForJIT();
207   
208   // Add common CodeGen passes.
209   if (addCommonCodeGenPasses(PM, OptLevel))
210     return true;
211
212   addCodeEmitter(PM, OptLevel, MCE);
213   if (PrintEmittedAsm)
214     addAssemblyEmitter(PM, OptLevel, true, ferrs());
215
216   PM.add(createGCInfoDeleter());
217
218   return false; // success!
219 }
220
221 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
222 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
223 /// actually outputting the machine code and resolving things like the address
224 /// of functions.  This method should returns true if machine code emission is
225 /// not supported.
226 ///
227 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
228                                                    JITCodeEmitter &JCE,
229                                                    CodeGenOpt::Level OptLevel) {
230   // Make sure the code model is set.
231   setCodeModelForJIT();
232   
233   // Add common CodeGen passes.
234   if (addCommonCodeGenPasses(PM, OptLevel))
235     return true;
236
237   addCodeEmitter(PM, OptLevel, JCE);
238   if (PrintEmittedAsm)
239     addAssemblyEmitter(PM, OptLevel, true, ferrs());
240
241   PM.add(createGCInfoDeleter());
242
243   return false; // success!
244 }
245
246 static void printAndVerify(PassManagerBase &PM,
247                            const char *Banner,
248                            bool allowDoubleDefs = false) {
249   if (PrintMachineCode)
250     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
251
252   if (VerifyMachineCode)
253     PM.add(createMachineVerifierPass(allowDoubleDefs));
254 }
255
256 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
257 /// emitting to assembly files or machine code output.
258 ///
259 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
260                                                CodeGenOpt::Level OptLevel) {
261   // Standard LLVM-Level Passes.
262
263   // Optionally, tun split-GEPs and no-load GVN.
264   if (EnableSplitGEPGVN) {
265     PM.add(createGEPSplitterPass());
266     PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
267   }
268
269   // Run loop strength reduction before anything else.
270   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
271     PM.add(createLoopStrengthReducePass(getTargetLowering()));
272     if (PrintLSR)
273       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
274   }
275
276   // Turn exception handling constructs into something the code generators can
277   // handle.
278   switch (getMCAsmInfo()->getExceptionHandlingType())
279   {
280   case ExceptionHandling::SjLj:
281     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
282     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
283     PM.add(createSjLjEHPass(getTargetLowering()));
284     break;
285   case ExceptionHandling::Dwarf:
286     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
287     break;
288   case ExceptionHandling::None:
289     PM.add(createLowerInvokePass(getTargetLowering()));
290     break;
291   }
292
293   PM.add(createGCLoweringPass());
294
295   // Make sure that no unreachable blocks are instruction selected.
296   PM.add(createUnreachableBlockEliminationPass());
297
298   if (OptLevel != CodeGenOpt::None && !DisableCGP)
299     PM.add(createCodeGenPreparePass(getTargetLowering()));
300
301   PM.add(createStackProtectorPass(getTargetLowering()));
302
303   if (PrintISelInput)
304     PM.add(createPrintFunctionPass("\n\n"
305                                    "*** Final LLVM Code input to ISel ***\n",
306                                    &dbgs()));
307
308   // Standard Lower-Level Passes.
309
310   // Set up a MachineFunction for the rest of CodeGen to work on.
311   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
312
313   // Enable FastISel with -fast, but allow that to be overridden.
314   if (EnableFastISelOption == cl::BOU_TRUE ||
315       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
316     EnableFastISel = true;
317
318   // Ask the target for an isel.
319   if (addInstSelector(PM, OptLevel))
320     return true;
321
322   // Print the instruction selected machine code...
323   printAndVerify(PM, "After Instruction Selection",
324                  /* allowDoubleDefs= */ true);
325
326   if (OptLevel != CodeGenOpt::None) {
327     if (!DisableMachineLICM)
328       PM.add(createMachineLICMPass());
329     if (!DisableMachineSink)
330       PM.add(createMachineSinkingPass());
331     printAndVerify(PM, "After MachineLICM and MachineSinking",
332                    /* allowDoubleDefs= */ true);
333   }
334
335   // Pre-ra tail duplication.
336   if (OptLevel != CodeGenOpt::None &&
337       !DisableTailDuplicate && PreAllocTailDup) {
338     PM.add(createTailDuplicatePass(true));
339     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
340                    /* allowDoubleDefs= */ true);
341   }
342
343   // Run pre-ra passes.
344   if (addPreRegAlloc(PM, OptLevel))
345     printAndVerify(PM, "After PreRegAlloc passes",
346                    /* allowDoubleDefs= */ true);
347
348   // Perform register allocation.
349   PM.add(createRegisterAllocator());
350   printAndVerify(PM, "After Register Allocation");
351
352   // Perform stack slot coloring.
353   if (OptLevel != CodeGenOpt::None && !DisableSSC) {
354     // FIXME: Re-enable coloring with register when it's capable of adding
355     // kill markers.
356     PM.add(createStackSlotColoringPass(false));
357     printAndVerify(PM, "After StackSlotColoring");
358   }
359
360   // Run post-ra passes.
361   if (addPostRegAlloc(PM, OptLevel))
362     printAndVerify(PM, "After PostRegAlloc passes");
363
364   PM.add(createLowerSubregsPass());
365   printAndVerify(PM, "After LowerSubregs");
366
367   // Insert prolog/epilog code.  Eliminate abstract frame index references...
368   PM.add(createPrologEpilogCodeInserter());
369   printAndVerify(PM, "After PrologEpilogCodeInserter");
370
371   // Run pre-sched2 passes.
372   if (addPreSched2(PM, OptLevel))
373     printAndVerify(PM, "After PreSched2 passes");
374
375   // Second pass scheduler.
376   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
377     PM.add(createPostRAScheduler(OptLevel));
378     printAndVerify(PM, "After PostRAScheduler");
379   }
380
381   // Branch folding must be run after regalloc and prolog/epilog insertion.
382   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
383     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
384     printAndVerify(PM, "After BranchFolding");
385   }
386
387   // Tail duplication.
388   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
389     PM.add(createTailDuplicatePass(false));
390     printAndVerify(PM, "After TailDuplicate");
391   }
392
393   PM.add(createGCMachineCodeAnalysisPass());
394
395   if (PrintGCInfo)
396     PM.add(createGCInfoPrinter(dbgs()));
397
398   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
399     PM.add(createCodePlacementOptPass());
400     printAndVerify(PM, "After CodePlacementOpt");
401   }
402
403   if (addPreEmitPass(PM, OptLevel))
404     printAndVerify(PM, "After PreEmit passes");
405
406   return false;
407 }