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