LLVMTargetMachine.cpp revision 5694b479aaa0214543571f21b51098015514f1b4
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/Pass.h"
17#include "llvm/Assembly/PrintModulePass.h"
18#include "llvm/CodeGen/AsmPrinter.h"
19#include "llvm/CodeGen/Passes.h"
20#include "llvm/CodeGen/FileWriters.h"
21#include "llvm/CodeGen/GCStrategy.h"
22#include "llvm/CodeGen/MachineFunctionAnalysis.h"
23#include "llvm/Target/TargetOptions.h"
24#include "llvm/MC/MCAsmInfo.h"
25#include "llvm/Target/TargetRegistry.h"
26#include "llvm/Transforms/Scalar.h"
27#include "llvm/Support/CommandLine.h"
28#include "llvm/Support/Debug.h"
29#include "llvm/Support/FormattedStream.h"
30using namespace llvm;
31
32namespace llvm {
33  bool EnableFastISel;
34}
35
36static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
37    cl::desc("Disable Post Regalloc"));
38static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
39    cl::desc("Disable branch folding"));
40static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
41    cl::desc("Disable tail duplication"));
42static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
43    cl::desc("Disable code placement"));
44static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
45    cl::desc("Disable Stack Slot Coloring"));
46static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
47    cl::desc("Disable Machine LICM"));
48static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
49    cl::desc("Disable Machine Sinking"));
50static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
51    cl::desc("Disable Loop Strength Reduction Pass"));
52static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
53    cl::desc("Disable Codegen Prepare"));
54static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
55    cl::desc("Print LLVM IR produced by the loop-reduce pass"));
56static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
57    cl::desc("Print LLVM IR input to isel pass"));
58static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
59    cl::desc("Dump emitter generated instructions as assembly"));
60static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
61    cl::desc("Dump garbage collector data"));
62static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
63    cl::desc("Verify generated machine code"),
64    cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
65
66
67// Enable or disable FastISel. Both options are needed, because
68// FastISel is enabled by default with -fast, and we wish to be
69// able to enable or disable fast-isel independently from -O0.
70static cl::opt<cl::boolOrDefault>
71EnableFastISelOption("fast-isel", cl::Hidden,
72  cl::desc("Enable the \"fast\" instruction selector"));
73
74// Enable or disable an experimental optimization to split GEPs
75// and run a special GVN pass which does not examine loads, in
76// an effort to factor out redundancy implicit in complex GEPs.
77static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
78    cl::desc("Split GEPs and run no-load GVN"));
79
80static cl::opt<bool> PreAllocTailDup("pre-regalloc-taildup", cl::Hidden,
81    cl::desc("Pre-register allocation tail duplication"));
82
83LLVMTargetMachine::LLVMTargetMachine(const Target &T,
84                                     const std::string &TargetTriple)
85  : TargetMachine(T) {
86  AsmInfo = T.createAsmInfo(TargetTriple);
87}
88
89// Set the default code model for the JIT for a generic target.
90// FIXME: Is small right here? or .is64Bit() ? Large : Small?
91void
92LLVMTargetMachine::setCodeModelForJIT() {
93  setCodeModel(CodeModel::Small);
94}
95
96// Set the default code model for static compilation for a generic target.
97void
98LLVMTargetMachine::setCodeModelForStatic() {
99  setCodeModel(CodeModel::Small);
100}
101
102FileModel::Model
103LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
104                                       formatted_raw_ostream &Out,
105                                       CodeGenFileType FileType,
106                                       CodeGenOpt::Level OptLevel) {
107  // Add common CodeGen passes.
108  if (addCommonCodeGenPasses(PM, OptLevel))
109    return FileModel::Error;
110
111  switch (FileType) {
112  default:
113    break;
114  case TargetMachine::AssemblyFile:
115    if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
116      return FileModel::Error;
117    return FileModel::AsmFile;
118  case TargetMachine::ObjectFile:
119    if (!addObjectFileEmitter(PM, OptLevel, Out))
120      return FileModel::MachOFile;
121    else if (getELFWriterInfo())
122      return FileModel::ElfFile;
123  }
124  return FileModel::Error;
125}
126
127bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
128                                           CodeGenOpt::Level OptLevel,
129                                           bool Verbose,
130                                           formatted_raw_ostream &Out) {
131  FunctionPass *Printer =
132    getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
133  if (!Printer)
134    return true;
135
136  PM.add(Printer);
137  return false;
138}
139
140bool LLVMTargetMachine::addObjectFileEmitter(PassManagerBase &PM,
141                                             CodeGenOpt::Level OptLevel,
142                                             formatted_raw_ostream &Out) {
143  MCCodeEmitter *Emitter = getTarget().createCodeEmitter(*this);
144  if (!Emitter)
145    return true;
146
147  PM.add(createMachOWriter(Out, *this, getMCAsmInfo(), Emitter));
148  return false;
149}
150
151/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
152/// be split up (e.g., to add an object writer pass), this method can be used to
153/// finish up adding passes to emit the file, if necessary.
154bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
155                                                  MachineCodeEmitter *MCE,
156                                                  CodeGenOpt::Level OptLevel) {
157  // Make sure the code model is set.
158  setCodeModelForStatic();
159
160  if (MCE)
161    addSimpleCodeEmitter(PM, OptLevel, *MCE);
162  if (PrintEmittedAsm)
163    addAssemblyEmitter(PM, OptLevel, true, ferrs());
164
165  PM.add(createGCInfoDeleter());
166
167  return false; // success!
168}
169
170/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
171/// be split up (e.g., to add an object writer pass), this method can be used to
172/// finish up adding passes to emit the file, if necessary.
173bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
174                                                  JITCodeEmitter *JCE,
175                                                  CodeGenOpt::Level OptLevel) {
176  // Make sure the code model is set.
177  setCodeModelForJIT();
178
179  if (JCE)
180    addSimpleCodeEmitter(PM, OptLevel, *JCE);
181  if (PrintEmittedAsm)
182    addAssemblyEmitter(PM, OptLevel, true, ferrs());
183
184  PM.add(createGCInfoDeleter());
185
186  return false; // success!
187}
188
189/// addPassesToEmitFileFinish - If the passes to emit the specified file had to
190/// be split up (e.g., to add an object writer pass), this method can be used to
191/// finish up adding passes to emit the file, if necessary.
192bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
193                                                  ObjectCodeEmitter *OCE,
194                                                  CodeGenOpt::Level OptLevel) {
195  // Make sure the code model is set.
196  setCodeModelForStatic();
197
198  if (OCE)
199    addSimpleCodeEmitter(PM, OptLevel, *OCE);
200  if (PrintEmittedAsm)
201    addAssemblyEmitter(PM, OptLevel, true, ferrs());
202
203  PM.add(createGCInfoDeleter());
204
205  return false; // success!
206}
207
208/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
209/// get machine code emitted.  This uses a MachineCodeEmitter object to handle
210/// actually outputting the machine code and resolving things like the address
211/// of functions.  This method should returns true if machine code emission is
212/// not supported.
213///
214bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
215                                                   MachineCodeEmitter &MCE,
216                                                   CodeGenOpt::Level OptLevel) {
217  // Make sure the code model is set.
218  setCodeModelForJIT();
219
220  // Add common CodeGen passes.
221  if (addCommonCodeGenPasses(PM, OptLevel))
222    return true;
223
224  addCodeEmitter(PM, OptLevel, MCE);
225  if (PrintEmittedAsm)
226    addAssemblyEmitter(PM, OptLevel, true, ferrs());
227
228  PM.add(createGCInfoDeleter());
229
230  return false; // success!
231}
232
233/// addPassesToEmitMachineCode - Add passes to the specified pass manager to
234/// get machine code emitted.  This uses a MachineCodeEmitter object to handle
235/// actually outputting the machine code and resolving things like the address
236/// of functions.  This method should returns true if machine code emission is
237/// not supported.
238///
239bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
240                                                   JITCodeEmitter &JCE,
241                                                   CodeGenOpt::Level OptLevel) {
242  // Make sure the code model is set.
243  setCodeModelForJIT();
244
245  // Add common CodeGen passes.
246  if (addCommonCodeGenPasses(PM, OptLevel))
247    return true;
248
249  addCodeEmitter(PM, OptLevel, JCE);
250  if (PrintEmittedAsm)
251    addAssemblyEmitter(PM, OptLevel, true, ferrs());
252
253  PM.add(createGCInfoDeleter());
254
255  return false; // success!
256}
257
258static void printAndVerify(PassManagerBase &PM,
259                           const char *Banner,
260                           bool allowDoubleDefs = false) {
261  if (PrintMachineCode)
262    PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
263
264  if (VerifyMachineCode)
265    PM.add(createMachineVerifierPass(allowDoubleDefs));
266}
267
268/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
269/// emitting to assembly files or machine code output.
270///
271bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
272                                               CodeGenOpt::Level OptLevel) {
273  // Standard LLVM-Level Passes.
274
275  // Optionally, tun split-GEPs and no-load GVN.
276  if (EnableSplitGEPGVN) {
277    PM.add(createGEPSplitterPass());
278    PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
279  }
280
281  // Run loop strength reduction before anything else.
282  if (OptLevel != CodeGenOpt::None && !DisableLSR) {
283    PM.add(createLoopStrengthReducePass(getTargetLowering()));
284    if (PrintLSR)
285      PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
286  }
287
288  // Turn exception handling constructs into something the code generators can
289  // handle.
290  switch (getMCAsmInfo()->getExceptionHandlingType())
291  {
292  case ExceptionHandling::SjLj:
293    // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
294    // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
295    // catch info can get misplaced when a selector ends up more than one block
296    // removed from the parent invoke(s). This could happen when a landing
297    // pad is shared by multiple invokes and is also a target of a normal
298    // edge from elsewhere.
299    PM.add(createSjLjEHPass(getTargetLowering()));
300    PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
301    break;
302  case ExceptionHandling::Dwarf:
303    PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
304    break;
305  case ExceptionHandling::None:
306    PM.add(createLowerInvokePass(getTargetLowering()));
307    break;
308  }
309
310  PM.add(createGCLoweringPass());
311
312  // Make sure that no unreachable blocks are instruction selected.
313  PM.add(createUnreachableBlockEliminationPass());
314
315  if (OptLevel != CodeGenOpt::None && !DisableCGP)
316    PM.add(createCodeGenPreparePass(getTargetLowering()));
317
318  PM.add(createStackProtectorPass(getTargetLowering()));
319
320  if (PrintISelInput)
321    PM.add(createPrintFunctionPass("\n\n"
322                                   "*** Final LLVM Code input to ISel ***\n",
323                                   &dbgs()));
324
325  // Standard Lower-Level Passes.
326
327  // Set up a MachineFunction for the rest of CodeGen to work on.
328  PM.add(new MachineFunctionAnalysis(*this, OptLevel));
329
330  // Enable FastISel with -fast, but allow that to be overridden.
331  if (EnableFastISelOption == cl::BOU_TRUE ||
332      (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
333    EnableFastISel = true;
334
335  // Ask the target for an isel.
336  if (addInstSelector(PM, OptLevel))
337    return true;
338
339  // Print the instruction selected machine code...
340  printAndVerify(PM, "After Instruction Selection",
341                 /* allowDoubleDefs= */ true);
342
343  if (OptLevel != CodeGenOpt::None) {
344    PM.add(createOptimizeExtsPass());
345    if (!DisableMachineLICM)
346      PM.add(createMachineLICMPass());
347    if (!DisableMachineSink)
348      PM.add(createMachineSinkingPass());
349    printAndVerify(PM, "After MachineLICM and MachineSinking",
350                   /* allowDoubleDefs= */ true);
351  }
352
353  // Pre-ra tail duplication.
354  if (OptLevel != CodeGenOpt::None &&
355      !DisableTailDuplicate && PreAllocTailDup) {
356    PM.add(createTailDuplicatePass(true));
357    printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
358                   /* allowDoubleDefs= */ true);
359  }
360
361  // Run pre-ra passes.
362  if (addPreRegAlloc(PM, OptLevel))
363    printAndVerify(PM, "After PreRegAlloc passes",
364                   /* allowDoubleDefs= */ true);
365
366  // Perform register allocation.
367  PM.add(createRegisterAllocator());
368  printAndVerify(PM, "After Register Allocation");
369
370  // Perform stack slot coloring.
371  if (OptLevel != CodeGenOpt::None && !DisableSSC) {
372    // FIXME: Re-enable coloring with register when it's capable of adding
373    // kill markers.
374    PM.add(createStackSlotColoringPass(false));
375    printAndVerify(PM, "After StackSlotColoring");
376  }
377
378  // Run post-ra passes.
379  if (addPostRegAlloc(PM, OptLevel))
380    printAndVerify(PM, "After PostRegAlloc passes");
381
382  PM.add(createLowerSubregsPass());
383  printAndVerify(PM, "After LowerSubregs");
384
385  // Insert prolog/epilog code.  Eliminate abstract frame index references...
386  PM.add(createPrologEpilogCodeInserter());
387  printAndVerify(PM, "After PrologEpilogCodeInserter");
388
389  // Run pre-sched2 passes.
390  if (addPreSched2(PM, OptLevel))
391    printAndVerify(PM, "After PreSched2 passes");
392
393  // Second pass scheduler.
394  if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
395    PM.add(createPostRAScheduler(OptLevel));
396    printAndVerify(PM, "After PostRAScheduler");
397  }
398
399  // Branch folding must be run after regalloc and prolog/epilog insertion.
400  if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
401    PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
402    printAndVerify(PM, "After BranchFolding");
403  }
404
405  // Tail duplication.
406  if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
407    PM.add(createTailDuplicatePass(false));
408    printAndVerify(PM, "After TailDuplicate");
409  }
410
411  PM.add(createGCMachineCodeAnalysisPass());
412
413  if (PrintGCInfo)
414    PM.add(createGCInfoPrinter(dbgs()));
415
416  if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
417    PM.add(createCodePlacementOptPass());
418    printAndVerify(PM, "After CodePlacementOpt");
419  }
420
421  if (addPreEmitPass(PM, OptLevel))
422    printAndVerify(PM, "After PreEmit passes");
423
424  return false;
425}
426