Manage MachineFunctions with an analysis Pass instead of the Annotable
[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/Analysis/LoopPass.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/Target/TargetAsmInfo.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> PrintLSR("print-lsr-output", cl::Hidden,
35     cl::desc("Print LLVM IR produced by the loop-reduce pass"));
36 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
37     cl::desc("Print LLVM IR input to isel pass"));
38 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
39     cl::desc("Dump emitter generated instructions as assembly"));
40 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
41     cl::desc("Dump garbage collector data"));
42 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
43     cl::desc("Verify generated machine code"),
44     cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
45
46 // When this works it will be on by default.
47 static cl::opt<bool>
48 DisablePostRAScheduler("disable-post-RA-scheduler",
49                        cl::desc("Disable scheduling after register allocation"),
50                        cl::init(true));
51
52 // Enable or disable FastISel. Both options are needed, because
53 // FastISel is enabled by default with -fast, and we wish to be
54 // able to enable or disable fast-isel independently from -fast.
55 static cl::opt<cl::boolOrDefault>
56 EnableFastISelOption("fast-isel", cl::Hidden,
57   cl::desc("Enable the experimental \"fast\" instruction selector"));
58
59 FileModel::Model
60 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
61                                        formatted_raw_ostream &Out,
62                                        CodeGenFileType FileType,
63                                        CodeGenOpt::Level OptLevel) {
64   // Add common CodeGen passes.
65   if (addCommonCodeGenPasses(PM, OptLevel))
66     return FileModel::Error;
67
68   // Fold redundant debug labels.
69   PM.add(createDebugLabelFoldingPass());
70
71   if (PrintMachineCode)
72     PM.add(createMachineFunctionPrinterPass(cerr));
73
74   if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
75     PM.add(createMachineFunctionPrinterPass(cerr));
76
77   if (OptLevel != CodeGenOpt::None)
78     PM.add(createCodePlacementOptPass());
79
80   switch (FileType) {
81   default:
82     break;
83   case TargetMachine::AssemblyFile:
84     if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
85       return FileModel::Error;
86     return FileModel::AsmFile;
87   case TargetMachine::ObjectFile:
88     if (getMachOWriterInfo())
89       return FileModel::MachOFile;
90     else if (getELFWriterInfo())
91       return FileModel::ElfFile;
92   }
93
94   return FileModel::Error;
95 }
96
97 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
98                                            CodeGenOpt::Level OptLevel,
99                                            bool Verbose,
100                                            formatted_raw_ostream &Out) {
101   FunctionPass *Printer = getTarget().createAsmPrinter(Out, *this, Verbose);
102   if (!Printer)
103     return true;
104
105   PM.add(Printer);
106   return false;
107 }
108
109 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
110 /// be split up (e.g., to add an object writer pass), this method can be used to
111 /// finish up adding passes to emit the file, if necessary.
112 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
113                                                   MachineCodeEmitter *MCE,
114                                                   CodeGenOpt::Level OptLevel) {
115   if (MCE)
116     addSimpleCodeEmitter(PM, OptLevel, *MCE);
117   if (PrintEmittedAsm)
118     addAssemblyEmitter(PM, OptLevel, true, ferrs());
119
120   PM.add(createGCInfoDeleter());
121
122   return false; // success!
123 }
124
125 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
126 /// be split up (e.g., to add an object writer pass), this method can be used to
127 /// finish up adding passes to emit the file, if necessary.
128 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
129                                                   JITCodeEmitter *JCE,
130                                                   CodeGenOpt::Level OptLevel) {
131   if (JCE)
132     addSimpleCodeEmitter(PM, OptLevel, *JCE);
133   if (PrintEmittedAsm)
134     addAssemblyEmitter(PM, OptLevel, true, ferrs());
135
136   PM.add(createGCInfoDeleter());
137
138   return false; // success!
139 }
140
141 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
142 /// be split up (e.g., to add an object writer pass), this method can be used to
143 /// finish up adding passes to emit the file, if necessary.
144 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
145                                                   ObjectCodeEmitter *OCE,
146                                                   CodeGenOpt::Level OptLevel) {
147   if (OCE)
148     addSimpleCodeEmitter(PM, OptLevel, *OCE);
149   if (PrintEmittedAsm)
150     addAssemblyEmitter(PM, OptLevel, true, ferrs());
151
152   PM.add(createGCInfoDeleter());
153
154   return false; // success!
155 }
156
157 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
158 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
159 /// actually outputting the machine code and resolving things like the address
160 /// of functions.  This method should returns true if machine code emission is
161 /// not supported.
162 ///
163 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
164                                                    MachineCodeEmitter &MCE,
165                                                    CodeGenOpt::Level OptLevel) {
166   // Add common CodeGen passes.
167   if (addCommonCodeGenPasses(PM, OptLevel))
168     return true;
169
170   if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
171     PM.add(createMachineFunctionPrinterPass(cerr));
172
173   addCodeEmitter(PM, OptLevel, MCE);
174   if (PrintEmittedAsm)
175     addAssemblyEmitter(PM, OptLevel, true, ferrs());
176
177   PM.add(createGCInfoDeleter());
178
179   return false; // success!
180 }
181
182 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
183 /// get machine code emitted.  This uses a MachineCodeEmitter object to handle
184 /// actually outputting the machine code and resolving things like the address
185 /// of functions.  This method should returns true if machine code emission is
186 /// not supported.
187 ///
188 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
189                                                    JITCodeEmitter &JCE,
190                                                    CodeGenOpt::Level OptLevel) {
191   // Add common CodeGen passes.
192   if (addCommonCodeGenPasses(PM, OptLevel))
193     return true;
194
195   if (addPreEmitPass(PM, OptLevel) && PrintMachineCode)
196     PM.add(createMachineFunctionPrinterPass(cerr));
197
198   addCodeEmitter(PM, OptLevel, JCE);
199   if (PrintEmittedAsm)
200     addAssemblyEmitter(PM, OptLevel, true, ferrs());
201
202   PM.add(createGCInfoDeleter());
203
204   return false; // success!
205 }
206
207 static void printAndVerify(PassManagerBase &PM,
208                            bool allowDoubleDefs = false) {
209   if (PrintMachineCode)
210     PM.add(createMachineFunctionPrinterPass(cerr));
211
212   if (VerifyMachineCode)
213     PM.add(createMachineVerifierPass(allowDoubleDefs));
214 }
215
216 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
217 /// emitting to assembly files or machine code output.
218 ///
219 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
220                                                CodeGenOpt::Level OptLevel) {
221   // Standard LLVM-Level Passes.
222
223   // Run loop strength reduction before anything else.
224   if (OptLevel != CodeGenOpt::None) {
225     PM.add(createLoopStrengthReducePass(getTargetLowering()));
226     if (PrintLSR)
227       PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
228   }
229
230   // Turn exception handling constructs into something the code generators can
231   // handle.
232   if (!getTargetAsmInfo()->doesSupportExceptionHandling())
233     PM.add(createLowerInvokePass(getTargetLowering()));
234   else
235     PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
236
237   PM.add(createGCLoweringPass());
238
239   // Make sure that no unreachable blocks are instruction selected.
240   PM.add(createUnreachableBlockEliminationPass());
241
242   if (OptLevel != CodeGenOpt::None)
243     PM.add(createCodeGenPreparePass(getTargetLowering()));
244
245   PM.add(createStackProtectorPass(getTargetLowering()));
246
247   if (PrintISelInput)
248     PM.add(createPrintFunctionPass("\n\n"
249                                    "*** Final LLVM Code input to ISel ***\n",
250                                    &errs()));
251
252   // Standard Lower-Level Passes.
253
254   // Set up a MachineFunction for the rest of CodeGen to work on.
255   PM.add(new MachineFunctionAnalysis(*this, OptLevel));
256
257   // Enable FastISel with -fast, but allow that to be overridden.
258   if (EnableFastISelOption == cl::BOU_TRUE ||
259       (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
260     EnableFastISel = true;
261
262   // Ask the target for an isel.
263   if (addInstSelector(PM, OptLevel))
264     return true;
265
266   // Print the instruction selected machine code...
267   printAndVerify(PM, /* allowDoubleDefs= */ true);
268
269   if (OptLevel != CodeGenOpt::None) {
270     PM.add(createMachineLICMPass());
271     PM.add(createMachineSinkingPass());
272     printAndVerify(PM, /* allowDoubleDefs= */ true);
273   }
274
275   // Run pre-ra passes.
276   if (addPreRegAlloc(PM, OptLevel))
277     printAndVerify(PM);
278
279   // Perform register allocation.
280   PM.add(createRegisterAllocator());
281
282   // Perform stack slot coloring.
283   if (OptLevel != CodeGenOpt::None)
284     PM.add(createStackSlotColoringPass(OptLevel >= CodeGenOpt::Aggressive));
285
286   printAndVerify(PM);           // Print the register-allocated code
287
288   // Run post-ra passes.
289   if (addPostRegAlloc(PM, OptLevel))
290     printAndVerify(PM);
291
292   PM.add(createLowerSubregsPass());
293   printAndVerify(PM);
294
295   // Insert prolog/epilog code.  Eliminate abstract frame index references...
296   PM.add(createPrologEpilogCodeInserter());
297   printAndVerify(PM);
298
299   // Second pass scheduler.
300   if (OptLevel != CodeGenOpt::None && !DisablePostRAScheduler) {
301     PM.add(createPostRAScheduler());
302     printAndVerify(PM);
303   }
304
305   // Branch folding must be run after regalloc and prolog/epilog insertion.
306   if (OptLevel != CodeGenOpt::None) {
307     PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
308     printAndVerify(PM);
309   }
310
311   PM.add(createGCMachineCodeAnalysisPass());
312   printAndVerify(PM);
313
314   if (PrintGCInfo)
315     PM.add(createGCInfoPrinter(*cerr));
316
317   return false;
318 }