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