This is the start of the new SjLj EH preparation pass, which will replace the
[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> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
49     cl::desc("Disable the old SjLj EH preparation pass"));
50
51 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
52     cl::desc("Disable Post Regalloc"));
53 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
54     cl::desc("Disable branch folding"));
55 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
56     cl::desc("Disable tail duplication"));
57 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
58     cl::desc("Disable pre-register allocation tail duplication"));
59 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
60     cl::desc("Disable code placement"));
61 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
62     cl::desc("Disable Stack Slot Coloring"));
63 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
64     cl::desc("Disable Machine Dead Code Elimination"));
65 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
66     cl::desc("Disable Machine LICM"));
67 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
68     cl::desc("Disable Machine Common Subexpression Elimination"));
69 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
70     cl::Hidden,
71     cl::desc("Disable Machine LICM"));
72 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
73     cl::desc("Disable Machine Sinking"));
74 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
75     cl::desc("Disable Loop Strength Reduction Pass"));
76 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
77     cl::desc("Disable Codegen Prepare"));
78 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
79     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
80 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
81     cl::desc("Print LLVM IR input to isel pass"));
82 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
83     cl::desc("Dump garbage collector data"));
84 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
85     cl::desc("Show encoding in .s output"));
86 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
87     cl::desc("Show instruction structure in .s output"));
88 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
89     cl::desc("Enable MC API logging"));
90 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
91     cl::desc("Verify generated machine code"),
92     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
93
94 static cl::opt<cl::boolOrDefault>
95 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
96            cl::init(cl::BOU_UNSET));
97
98 static bool getVerboseAsm() {
99   switch (AsmVerbose) {
100   default:
101   case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
102   case cl::BOU_TRUE:  return true;
103   case cl::BOU_FALSE: return false;
104   }
105 }
106
107 // Enable or disable FastISel. Both options are needed, because
108 // FastISel is enabled by default with -fast, and we wish to be
109 // able to enable or disable fast-isel independently from -O0.
110 static cl::opt<cl::boolOrDefault>
111 EnableFastISelOption("fast-isel", cl::Hidden,
112   cl::desc("Enable the \"fast\" instruction selector"));
113
114 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
115                                      StringRef CPU, StringRef FS,
116                                      Reloc::Model RM, CodeModel::Model CM)
117   : TargetMachine(T, Triple, CPU, FS) {
118   CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM);
119   AsmInfo = T.createMCAsmInfo(Triple);
120 }
121
122 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
123                                             formatted_raw_ostream &Out,
124                                             CodeGenFileType FileType,
125                                             CodeGenOpt::Level OptLevel,
126                                             bool DisableVerify) {
127   // Add common CodeGen passes.
128   MCContext *Context = 0;
129   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
130     return true;
131   assert(Context != 0 && "Failed to get MCContext");
132
133   if (hasMCSaveTempLabels())
134     Context->setAllowTemporaryLabels(false);
135
136   const MCAsmInfo &MAI = *getMCAsmInfo();
137   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
138   OwningPtr<MCStreamer> AsmStreamer;
139
140   switch (FileType) {
141   default: return true;
142   case CGFT_AssemblyFile: {
143     MCInstPrinter *InstPrinter =
144       getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
145
146     // Create a code emitter if asked to show the encoding.
147     MCCodeEmitter *MCE = 0;
148     MCAsmBackend *MAB = 0;
149     if (ShowMCEncoding) {
150       const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
151       MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
152       MAB = getTarget().createMCAsmBackend(getTargetTriple());
153     }
154
155     MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
156                                                   getVerboseAsm(),
157                                                   hasMCUseLoc(),
158                                                   hasMCUseCFI(),
159                                                   InstPrinter,
160                                                   MCE, MAB,
161                                                   ShowMCInst);
162     AsmStreamer.reset(S);
163     break;
164   }
165   case CGFT_ObjectFile: {
166     // Create the code emitter for the target if it exists.  If not, .o file
167     // emission fails.
168     MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
169                                                          *Context);
170     MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
171     if (MCE == 0 || MAB == 0)
172       return true;
173
174     AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
175                                                          *Context, *MAB, Out,
176                                                          MCE, hasMCRelaxAll(),
177                                                          hasMCNoExecStack()));
178     AsmStreamer.get()->InitSections();
179     break;
180   }
181   case CGFT_Null:
182     // The Null output is intended for use for performance analysis and testing,
183     // not real users.
184     AsmStreamer.reset(createNullStreamer(*Context));
185     break;
186   }
187
188   if (EnableMCLogging)
189     AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
190
191   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
192   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
193   if (Printer == 0)
194     return true;
195
196   // If successful, createAsmPrinter took ownership of AsmStreamer.
197   AsmStreamer.take();
198
199   PM.add(Printer);
200
201   PM.add(createGCInfoDeleter());
202   return false;
203 }
204
205 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
206 /// get machine code emitted.  This uses a JITCodeEmitter object to handle
207 /// actually outputting the machine code and resolving things like the address
208 /// of functions.  This method should returns true if machine code emission is
209 /// not supported.
210 ///
211 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
212                                                    JITCodeEmitter &JCE,
213                                                    CodeGenOpt::Level OptLevel,
214                                                    bool DisableVerify) {
215   // Add common CodeGen passes.
216   MCContext *Ctx = 0;
217   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
218     return true;
219
220   addCodeEmitter(PM, OptLevel, JCE);
221   PM.add(createGCInfoDeleter());
222
223   return false; // success!
224 }
225
226 /// addPassesToEmitMC - Add passes to the specified pass manager to get
227 /// machine code emitted with the MCJIT. This method returns true if machine
228 /// code is not supported. It fills the MCContext Ctx pointer which can be
229 /// used to build custom MCStreamer.
230 ///
231 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
232                                           MCContext *&Ctx,
233                                           raw_ostream &Out,
234                                           CodeGenOpt::Level OptLevel,
235                                           bool DisableVerify) {
236   // Add common CodeGen passes.
237   if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
238     return true;
239
240   if (hasMCSaveTempLabels())
241     Ctx->setAllowTemporaryLabels(false);
242
243   // Create the code emitter for the target if it exists.  If not, .o file
244   // emission fails.
245   const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
246   MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
247   MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
248   if (MCE == 0 || MAB == 0)
249     return true;
250
251   OwningPtr<MCStreamer> AsmStreamer;
252   AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
253                                                        *MAB, Out, MCE,
254                                                        hasMCRelaxAll(),
255                                                        hasMCNoExecStack()));
256   AsmStreamer.get()->InitSections();
257
258   // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
259   FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
260   if (Printer == 0)
261     return true;
262
263   // If successful, createAsmPrinter took ownership of AsmStreamer.
264   AsmStreamer.take();
265
266   PM.add(Printer);
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     if (!DisableOldSjLjEH)
329       PM.add(createSjLjEHPass(getTargetLowering()));
330     // FALLTHROUGH
331   case ExceptionHandling::DwarfCFI:
332   case ExceptionHandling::ARM:
333   case ExceptionHandling::Win64:
334     PM.add(createDwarfEHPass(this));
335     break;
336   case ExceptionHandling::None:
337     PM.add(createLowerInvokePass(getTargetLowering()));
338
339     // The lower invoke pass may create unreachable code. Remove it.
340     PM.add(createUnreachableBlockEliminationPass());
341     break;
342   }
343
344   if (OptLevel != CodeGenOpt::None && !DisableCGP)
345     PM.add(createCodeGenPreparePass(getTargetLowering()));
346
347   PM.add(createStackProtectorPass(getTargetLowering()));
348
349   addPreISel(PM, OptLevel);
350
351   if (PrintISelInput)
352     PM.add(createPrintFunctionPass("\n\n"
353                                    "*** Final LLVM Code input to ISel ***\n",
354                                    &dbgs()));
355
356   // All passes which modify the LLVM IR are now complete; run the verifier
357   // to ensure that the IR is valid.
358   if (!DisableVerify)
359     PM.add(createVerifierPass());
360
361   // Standard Lower-Level Passes.
362
363   // Install a MachineModuleInfo class, which is an immutable pass that holds
364   // all the per-module stuff we're generating, including MCContext.
365   MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
366                                                  *getRegisterInfo(),
367                                      &getTargetLowering()->getObjFileLowering());
368   PM.add(MMI);
369   OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
370
371   // Set up a MachineFunction for the rest of CodeGen to work on.
372   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
373
374   // Enable FastISel with -fast, but allow that to be overridden.
375   if (EnableFastISelOption == cl::BOU_TRUE ||
376       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
377     EnableFastISel = true;
378
379   // Ask the target for an isel.
380   if (addInstSelector(PM, OptLevel))
381     return true;
382
383   // Print the instruction selected machine code...
384   printAndVerify(PM, "After Instruction Selection");
385
386   // Expand pseudo-instructions emitted by ISel.
387   PM.add(createExpandISelPseudosPass());
388
389   // Pre-ra tail duplication.
390   if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
391     PM.add(createTailDuplicatePass(true));
392     printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
393   }
394
395   // Optimize PHIs before DCE: removing dead PHI cycles may make more
396   // instructions dead.
397   if (OptLevel != CodeGenOpt::None)
398     PM.add(createOptimizePHIsPass());
399
400   // If the target requests it, assign local variables to stack slots relative
401   // to one another and simplify frame index references where possible.
402   PM.add(createLocalStackSlotAllocationPass());
403
404   if (OptLevel != CodeGenOpt::None) {
405     // With optimization, dead code should already be eliminated. However
406     // there is one known exception: lowered code for arguments that are only
407     // used by tail calls, where the tail calls reuse the incoming stack
408     // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
409     if (!DisableMachineDCE)
410       PM.add(createDeadMachineInstructionElimPass());
411     printAndVerify(PM, "After codegen DCE pass");
412
413     if (!DisableMachineLICM)
414       PM.add(createMachineLICMPass());
415     if (!DisableMachineCSE)
416       PM.add(createMachineCSEPass());
417     if (!DisableMachineSink)
418       PM.add(createMachineSinkingPass());
419     printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
420
421     PM.add(createPeepholeOptimizerPass());
422     printAndVerify(PM, "After codegen peephole optimization pass");
423   }
424
425   // Run pre-ra passes.
426   if (addPreRegAlloc(PM, OptLevel))
427     printAndVerify(PM, "After PreRegAlloc passes");
428
429   // Perform register allocation.
430   PM.add(createRegisterAllocator(OptLevel));
431   printAndVerify(PM, "After Register Allocation");
432
433   // Perform stack slot coloring and post-ra machine LICM.
434   if (OptLevel != CodeGenOpt::None) {
435     // FIXME: Re-enable coloring with register when it's capable of adding
436     // kill markers.
437     if (!DisableSSC)
438       PM.add(createStackSlotColoringPass(false));
439
440     // Run post-ra machine LICM to hoist reloads / remats.
441     if (!DisablePostRAMachineLICM)
442       PM.add(createMachineLICMPass(false));
443
444     printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
445   }
446
447   // Run post-ra passes.
448   if (addPostRegAlloc(PM, OptLevel))
449     printAndVerify(PM, "After PostRegAlloc passes");
450
451   PM.add(createExpandPostRAPseudosPass());
452   printAndVerify(PM, "After ExpandPostRAPseudos");
453
454   // Insert prolog/epilog code.  Eliminate abstract frame index references...
455   PM.add(createPrologEpilogCodeInserter());
456   printAndVerify(PM, "After PrologEpilogCodeInserter");
457
458   // Run pre-sched2 passes.
459   if (addPreSched2(PM, OptLevel))
460     printAndVerify(PM, "After PreSched2 passes");
461
462   // Second pass scheduler.
463   if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
464     PM.add(createPostRAScheduler(OptLevel));
465     printAndVerify(PM, "After PostRAScheduler");
466   }
467
468   // Branch folding must be run after regalloc and prolog/epilog insertion.
469   if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
470     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
471     printNoVerify(PM, "After BranchFolding");
472   }
473
474   // Tail duplication.
475   if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
476     PM.add(createTailDuplicatePass(false));
477     printNoVerify(PM, "After TailDuplicate");
478   }
479
480   PM.add(createGCMachineCodeAnalysisPass());
481
482   if (PrintGCInfo)
483     PM.add(createGCInfoPrinter(dbgs()));
484
485   if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
486     PM.add(createCodePlacementOptPass());
487     printNoVerify(PM, "After CodePlacementOpt");
488   }
489
490   if (addPreEmitPass(PM, OptLevel))
491     printNoVerify(PM, "After PreEmit passes");
492
493   return false;
494 }