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