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