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