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