5b2d40b5857f8fce0183e2c9c42d46a10633fe74
[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/Analysis/Verifier.h"
17 #include "llvm/Assembly/PrintModulePass.h"
18 #include "llvm/CodeGen/AsmPrinter.h"
19 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
20 #include "llvm/CodeGen/MachineModuleInfo.h"
21 #include "llvm/CodeGen/GCStrategy.h"
22 #include "llvm/CodeGen/Passes.h"
23 #include "llvm/Target/TargetOptions.h"
24 #include "llvm/MC/MCAsmInfo.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> DisablePostRAMachineLICM("disable-postra-machine-licm",
54     cl::Hidden,
55     cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
57     cl::desc("Disable Machine Sinking"));
58 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
59     cl::desc("Disable Loop Strength Reduction Pass"));
60 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
61     cl::desc("Disable Codegen Prepare"));
62 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
63     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
64 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
65     cl::desc("Print LLVM IR input to isel pass"));
66 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
67     cl::desc("Dump garbage collector data"));
68 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
69     cl::desc("Show encoding in .s output"));
70 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
71     cl::desc("Show instruction structure in .s output"));
72 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
73     cl::desc("Enable MC API logging"));
74 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
75     cl::desc("Verify generated machine code"),
76     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
77
78 static cl::opt<cl::boolOrDefault>
79 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
80            cl::init(cl::BOU_UNSET));
81
82 static bool getVerboseAsm() {
83   switch (AsmVerbose) {
84   default:
85   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
86   case cl::BOU_TRUE:  return true;
87   case cl::BOU_FALSE: return false;
88   }      
89 }
90
91 // Enable or disable FastISel. Both options are needed, because
92 // FastISel is enabled by default with -fast, and we wish to be
93 // able to enable or disable fast-isel independently from -O0.
94 static cl::opt<cl::boolOrDefault>
95 EnableFastISelOption("fast-isel", cl::Hidden,
96   cl::desc("Enable the \"fast\" instruction selector"));
97
98 // Enable or disable an experimental optimization to split GEPs
99 // and run a special GVN pass which does not examine loads, in
100 // an effort to factor out redundancy implicit in complex GEPs.
101 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
102     cl::desc("Split GEPs and run no-load GVN"));
103
104 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
105                                      const std::string &Triple)
106   : TargetMachine(T), TargetTriple(Triple) {
107   AsmInfo = T.createAsmInfo(TargetTriple);
108 }
109
110 // Set the default code model for the JIT for a generic target.
111 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
112 void LLVMTargetMachine::setCodeModelForJIT() {
113   setCodeModel(CodeModel::Small);
114 }
115
116 // Set the default code model for static compilation for a generic target.
117 void LLVMTargetMachine::setCodeModelForStatic() {
118   setCodeModel(CodeModel::Small);
119 }
120
121 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
122                                             formatted_raw_ostream &Out,
123                                             CodeGenFileType FileType,
124                                             CodeGenOpt::Level OptLevel,
125                                             bool DisableVerify) {
126   // Add common CodeGen passes.
127   MCContext *Context = 0;
128   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
129     return true;
130   assert(Context != 0 && "Failed to get MCContext");
131
132   const MCAsmInfo &MAI = *getMCAsmInfo();
133   OwningPtr<MCStreamer> AsmStreamer;
134
135   switch (FileType) {
136   default: return true;
137   case CGFT_AssemblyFile: {
138     MCInstPrinter *InstPrinter =
139       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
140
141     // Create a code emitter if asked to show the encoding.
142     MCCodeEmitter *MCE = 0;
143     if (ShowMCEncoding)
144       MCE = getTarget().createCodeEmitter(*this, *Context);
145
146     AsmStreamer.reset(createAsmStreamer(*Context, Out,
147                                         getTargetData()->isLittleEndian(),
148                                         getVerboseAsm(), InstPrinter,
149                                         MCE, ShowMCInst));
150     break;
151   }
152   case CGFT_ObjectFile: {
153     // Create the code emitter for the target if it exists.  If not, .o file
154     // emission fails.
155     MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
156     TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
157     if (MCE == 0 || TAB == 0)
158       return true;
159
160     AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
161                                                        *TAB, Out, MCE,
162                                                        hasMCRelaxAll()));
163     break;
164   }
165   case CGFT_Null:
166     // The Null output is intended for use for performance analysis and testing,
167     // not real users.
168     AsmStreamer.reset(createNullStreamer(*Context));
169     break;
170   }
171
172   if (EnableMCLogging)
173     AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
174
175   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
176   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
177   if (Printer == 0)
178     return true;
179   
180   // If successful, createAsmPrinter took ownership of AsmStreamer.
181   AsmStreamer.take();
182   
183   PM.add(Printer);
184   
185   // Make sure the code model is set.
186   setCodeModelForStatic();
187   PM.add(createGCInfoDeleter());
188   return false;
189 }
190
191 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
192 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
193 /// actually outputting the machine code and resolving things like the address
194 /// of functions.  This method should returns true if machine code emission is
195 /// not supported.
196 ///
197 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
198                                                    JITCodeEmitter &JCE,
199                                                    CodeGenOpt::Level OptLevel,
200                                                    bool DisableVerify) {
201   // Make sure the code model is set.
202   setCodeModelForJIT();
203   
204   // Add common CodeGen passes.
205   MCContext *Ctx = 0;
206   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
207     return true;
208
209   addCodeEmitter(PM, OptLevel, JCE);
210   PM.add(createGCInfoDeleter());
211
212   return false; // success!
213 }
214
215 /// addPassesToEmitMC - Add passes to the specified pass manager to get
216 /// machine code emitted with the MCJIT. This method returns true if machine
217 /// code is not supported. It fills the MCContext Ctx pointer which can be
218 /// used to build custom MCStreamer.
219 ///
220 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
221                                           MCContext *&Ctx,
222                                           CodeGenOpt::Level OptLevel,
223                                           bool DisableVerify) {
224   // Add common CodeGen passes.
225   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
226     return true;
227   // Make sure the code model is set.
228   setCodeModelForJIT();
229
230   return false; // success!
231 }
232
233 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
234   if (PrintMachineCode)
235     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
236 }
237
238 static void printAndVerify(PassManagerBase &PM,
239                            const char *Banner) {
240   if (PrintMachineCode)
241     PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
242
243   if (VerifyMachineCode)
244     PM.add(createMachineVerifierPass());
245 }
246
247 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
248 /// emitting to assembly files or machine code output.
249 ///
250 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
251                                                CodeGenOpt::Level OptLevel,
252                                                bool DisableVerify,
253                                                MCContext *&OutContext) {
254   // Standard LLVM-Level Passes.
255
256   // Before running any passes, run the verifier to determine if the input
257   // coming from the front-end and/or optimizer is valid.
258   if (!DisableVerify)
259     PM.add(createVerifierPass());
260
261   // Optionally, tun split-GEPs and no-load GVN.
262   if (EnableSplitGEPGVN) {
263     PM.add(createGEPSplitterPass());
264     PM.add(createGVNPass(/*NoLoads=*/true));
265   }
266
267   // Run loop strength reduction before anything else.
268   if (OptLevel != CodeGenOpt::None && !DisableLSR) {
269     PM.add(createLoopStrengthReducePass(getTargetLowering()));
270     if (PrintLSR)
271       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
272   }
273
274   PM.add(createGCLoweringPass());
275
276   // Make sure that no unreachable blocks are instruction selected.
277   PM.add(createUnreachableBlockEliminationPass());
278
279   // Turn exception handling constructs into something the code generators can
280   // handle.
281   switch (getMCAsmInfo()->getExceptionHandlingType()) {
282   case ExceptionHandling::SjLj:
283     // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
284     // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
285     // catch info can get misplaced when a selector ends up more than one block
286     // removed from the parent invoke(s). This could happen when a landing
287     // pad is shared by multiple invokes and is also a target of a normal
288     // edge from elsewhere.
289     PM.add(createSjLjEHPass(getTargetLowering()));
290     // FALLTHROUGH
291   case ExceptionHandling::Dwarf:
292     PM.add(createDwarfEHPass(this, OptLevel==CodeGenOpt::None));
293     break;
294   case ExceptionHandling::None:
295     PM.add(createLowerInvokePass(getTargetLowering()));
296
297     // The lower invoke pass may create unreachable code. Remove it.
298     PM.add(createUnreachableBlockEliminationPass());
299     break;
300   }
301
302   if (OptLevel != CodeGenOpt::None && !DisableCGP)
303     PM.add(createCodeGenPreparePass(getTargetLowering()));
304
305   PM.add(createStackProtectorPass(getTargetLowering()));
306
307   addPreISel(PM, OptLevel);
308
309   if (PrintISelInput)
310     PM.add(createPrintFunctionPass("\n\n"
311                                    "*** Final LLVM Code input to ISel ***\n",
312                                    &dbgs()));
313
314   // All passes which modify the LLVM IR are now complete; run the verifier
315   // to ensure that the IR is valid.
316   if (!DisableVerify)
317     PM.add(createVerifierPass());
318
319   // Standard Lower-Level Passes.
320   
321   // Install a MachineModuleInfo class, which is an immutable pass that holds
322   // all the per-module stuff we're generating, including MCContext.
323   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo());
324   PM.add(MMI);
325   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
326   
327
328   // Set up a MachineFunction for the rest of CodeGen to work on.
329   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
330
331   // Enable FastISel with -fast, but allow that to be overridden.
332   if (EnableFastISelOption == cl::BOU_TRUE ||
333       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
334     EnableFastISel = true;
335
336   // Ask the target for an isel.
337   if (addInstSelector(PM, OptLevel))
338     return true;
339
340   // Print the instruction selected machine code...
341   printAndVerify(PM, "After Instruction Selection");
342
343   // Optimize PHIs before DCE: removing dead PHI cycles may make more
344   // instructions dead.
345   if (OptLevel != CodeGenOpt::None)
346     PM.add(createOptimizePHIsPass());
347
348   if (OptLevel != CodeGenOpt::None) {
349     // With optimization, dead code should already be eliminated. However
350     // there is one known exception: lowered code for arguments that are only
351     // used by tail calls, where the tail calls reuse the incoming stack
352     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
353     PM.add(createDeadMachineInstructionElimPass());
354     printAndVerify(PM, "After codegen DCE pass");
355
356     PM.add(createOptimizeExtsPass());
357     PM.add(createOptimizeCmpsPass());
358     if (!DisableMachineLICM)
359       PM.add(createMachineLICMPass());
360     PM.add(createMachineCSEPass());
361     if (!DisableMachineSink)
362       PM.add(createMachineSinkingPass());
363     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
364   }
365
366   // Pre-ra tail duplication.
367   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
368     PM.add(createTailDuplicatePass(true));
369     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
370   }
371
372   // Run pre-ra passes.
373   if (addPreRegAlloc(PM, OptLevel))
374     printAndVerify(PM, "After PreRegAlloc passes");
375
376   // Perform register allocation.
377   PM.add(createRegisterAllocator(OptLevel));
378   printAndVerify(PM, "After Register Allocation");
379
380   // Perform stack slot coloring and post-ra machine LICM.
381   if (OptLevel != CodeGenOpt::None) {
382     // FIXME: Re-enable coloring with register when it's capable of adding
383     // kill markers.
384     if (!DisableSSC)
385       PM.add(createStackSlotColoringPass(false));
386
387     // Run post-ra machine LICM to hoist reloads / remats.
388     if (!DisablePostRAMachineLICM)
389       PM.add(createMachineLICMPass(false));
390
391     printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
392   }
393
394   // Run post-ra passes.
395   if (addPostRegAlloc(PM, OptLevel))
396     printAndVerify(PM, "After PostRegAlloc passes");
397
398   PM.add(createLowerSubregsPass());
399   printAndVerify(PM, "After LowerSubregs");
400
401   // Insert prolog/epilog code.  Eliminate abstract frame index references...
402   PM.add(createPrologEpilogCodeInserter());
403   printAndVerify(PM, "After PrologEpilogCodeInserter");
404
405   // Run pre-sched2 passes.
406   if (addPreSched2(PM, OptLevel))
407     printAndVerify(PM, "After PreSched2 passes");
408
409   // Second pass scheduler.
410   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
411     PM.add(createPostRAScheduler(OptLevel));
412     printAndVerify(PM, "After PostRAScheduler");
413   }
414
415   // Branch folding must be run after regalloc and prolog/epilog insertion.
416   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
417     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
418     printNoVerify(PM, "After BranchFolding");
419   }
420
421   // Tail duplication.
422   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
423     PM.add(createTailDuplicatePass(false));
424     printNoVerify(PM, "After TailDuplicate");
425   }
426
427   PM.add(createGCMachineCodeAnalysisPass());
428
429   if (PrintGCInfo)
430     PM.add(createGCInfoPrinter(dbgs()));
431
432   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
433     PM.add(createCodePlacementOptPass());
434     printNoVerify(PM, "After CodePlacementOpt");
435   }
436
437   if (addPreEmitPass(PM, OptLevel))
438     printNoVerify(PM, "After PreEmit passes");
439
440   return false;
441 }