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