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