1 //===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // This file implements the LLVMTargetMachine class.
12 //===----------------------------------------------------------------------===//
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"
34 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
35 cl::desc("Disable Post Regalloc"));
36 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
37 cl::desc("Disable branch folding"));
38 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
39 cl::desc("Disable tail duplication"));
40 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
41 cl::desc("Disable code placement"));
42 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
43 cl::desc("Disable Stack Slot Coloring"));
44 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
45 cl::desc("Disable Machine LICM"));
46 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
47 cl::desc("Disable Machine Sinking"));
48 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
49 cl::desc("Disable Loop Strength Reduction Pass"));
50 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
51 cl::desc("Disable Codegen Prepare"));
52 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
53 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
54 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
55 cl::desc("Print LLVM IR input to isel pass"));
56 static cl::opt<bool> PrintEmittedAsm("print-emitted-asm", cl::Hidden,
57 cl::desc("Dump emitter generated instructions as assembly"));
58 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
59 cl::desc("Dump garbage collector data"));
60 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
61 cl::desc("Verify generated machine code"),
62 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
64 // Enable or disable FastISel. Both options are needed, because
65 // FastISel is enabled by default with -fast, and we wish to be
66 // able to enable or disable fast-isel independently from -O0.
67 static cl::opt<cl::boolOrDefault>
68 EnableFastISelOption("fast-isel", cl::Hidden,
69 cl::desc("Enable the \"fast\" instruction selector"));
71 // Enable or disable an experimental optimization to split GEPs
72 // and run a special GVN pass which does not examine loads, in
73 // an effort to factor out redundancy implicit in complex GEPs.
74 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
75 cl::desc("Split GEPs and run no-load GVN"));
77 static cl::opt<bool> PreAllocTailDup("pre-regalloc-taildup", cl::Hidden,
78 cl::desc("Pre-register allocation tail duplication"));
80 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
81 const std::string &TargetTriple)
83 AsmInfo = T.createAsmInfo(TargetTriple);
89 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
90 formatted_raw_ostream &Out,
91 CodeGenFileType FileType,
92 CodeGenOpt::Level OptLevel) {
93 // Add common CodeGen passes.
94 if (addCommonCodeGenPasses(PM, OptLevel))
95 return FileModel::Error;
100 case TargetMachine::AssemblyFile:
101 if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
102 return FileModel::Error;
103 return FileModel::AsmFile;
104 case TargetMachine::ObjectFile:
105 if (getMachOWriterInfo())
106 return FileModel::MachOFile;
107 else if (getELFWriterInfo())
108 return FileModel::ElfFile;
111 return FileModel::Error;
114 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
115 CodeGenOpt::Level OptLevel,
117 formatted_raw_ostream &Out) {
118 FunctionPass *Printer =
119 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
127 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
128 /// be split up (e.g., to add an object writer pass), this method can be used to
129 /// finish up adding passes to emit the file, if necessary.
130 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
131 MachineCodeEmitter *MCE,
132 CodeGenOpt::Level OptLevel) {
134 addSimpleCodeEmitter(PM, OptLevel, *MCE);
136 addAssemblyEmitter(PM, OptLevel, true, ferrs());
138 PM.add(createGCInfoDeleter());
140 return false; // success!
143 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
144 /// be split up (e.g., to add an object writer pass), this method can be used to
145 /// finish up adding passes to emit the file, if necessary.
146 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
148 CodeGenOpt::Level OptLevel) {
150 addSimpleCodeEmitter(PM, OptLevel, *JCE);
152 addAssemblyEmitter(PM, OptLevel, true, ferrs());
154 PM.add(createGCInfoDeleter());
156 return false; // success!
159 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
160 /// be split up (e.g., to add an object writer pass), this method can be used to
161 /// finish up adding passes to emit the file, if necessary.
162 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
163 ObjectCodeEmitter *OCE,
164 CodeGenOpt::Level OptLevel) {
166 addSimpleCodeEmitter(PM, OptLevel, *OCE);
168 addAssemblyEmitter(PM, OptLevel, true, ferrs());
170 PM.add(createGCInfoDeleter());
172 return false; // success!
175 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
176 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
177 /// actually outputting the machine code and resolving things like the address
178 /// of functions. This method should returns true if machine code emission is
181 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
182 MachineCodeEmitter &MCE,
183 CodeGenOpt::Level OptLevel) {
184 // Add common CodeGen passes.
185 if (addCommonCodeGenPasses(PM, OptLevel))
188 addCodeEmitter(PM, OptLevel, MCE);
190 addAssemblyEmitter(PM, OptLevel, true, ferrs());
192 PM.add(createGCInfoDeleter());
194 return false; // success!
197 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
198 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
199 /// actually outputting the machine code and resolving things like the address
200 /// of functions. This method should returns true if machine code emission is
203 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
205 CodeGenOpt::Level OptLevel) {
206 // Add common CodeGen passes.
207 if (addCommonCodeGenPasses(PM, OptLevel))
210 addCodeEmitter(PM, OptLevel, JCE);
212 addAssemblyEmitter(PM, OptLevel, true, ferrs());
214 PM.add(createGCInfoDeleter());
216 return false; // success!
219 static void printAndVerify(PassManagerBase &PM,
221 bool allowDoubleDefs = false) {
222 if (PrintMachineCode)
223 PM.add(createMachineFunctionPrinterPass(errs(), Banner));
225 if (VerifyMachineCode)
226 PM.add(createMachineVerifierPass(allowDoubleDefs));
229 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
230 /// emitting to assembly files or machine code output.
232 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
233 CodeGenOpt::Level OptLevel) {
234 // Standard LLVM-Level Passes.
236 // Optionally, tun split-GEPs and no-load GVN.
237 if (EnableSplitGEPGVN) {
238 PM.add(createGEPSplitterPass());
239 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
242 // Run loop strength reduction before anything else.
243 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
244 PM.add(createLoopStrengthReducePass(getTargetLowering()));
246 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
249 // Turn exception handling constructs into something the code generators can
251 switch (getMCAsmInfo()->getExceptionHandlingType())
253 case ExceptionHandling::SjLj:
254 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
255 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
256 PM.add(createSjLjEHPass(getTargetLowering()));
258 case ExceptionHandling::Dwarf:
259 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
261 case ExceptionHandling::None:
262 PM.add(createLowerInvokePass(getTargetLowering()));
266 PM.add(createGCLoweringPass());
268 // Make sure that no unreachable blocks are instruction selected.
269 PM.add(createUnreachableBlockEliminationPass());
271 if (OptLevel != CodeGenOpt::None && !DisableCGP)
272 PM.add(createCodeGenPreparePass(getTargetLowering()));
274 PM.add(createStackProtectorPass(getTargetLowering()));
277 PM.add(createPrintFunctionPass("\n\n"
278 "*** Final LLVM Code input to ISel ***\n",
281 // Standard Lower-Level Passes.
283 // Set up a MachineFunction for the rest of CodeGen to work on.
284 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
286 // Enable FastISel with -fast, but allow that to be overridden.
287 if (EnableFastISelOption == cl::BOU_TRUE ||
288 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
289 EnableFastISel = true;
291 // Ask the target for an isel.
292 if (addInstSelector(PM, OptLevel))
295 // Print the instruction selected machine code...
296 printAndVerify(PM, "After Instruction Selection",
297 /* allowDoubleDefs= */ true);
299 if (OptLevel != CodeGenOpt::None) {
300 if (!DisableMachineLICM)
301 PM.add(createMachineLICMPass());
302 if (!DisableMachineSink)
303 PM.add(createMachineSinkingPass());
304 printAndVerify(PM, "After MachineLICM and MachineSinking",
305 /* allowDoubleDefs= */ true);
308 // Pre-ra tail duplication.
309 if (OptLevel != CodeGenOpt::None &&
310 !DisableTailDuplicate && PreAllocTailDup) {
311 PM.add(createTailDuplicatePass(true));
312 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
315 // Run pre-ra passes.
316 if (addPreRegAlloc(PM, OptLevel))
317 printAndVerify(PM, "After PreRegAlloc passes",
318 /* allowDoubleDefs= */ true);
320 // Perform register allocation.
321 PM.add(createRegisterAllocator());
322 printAndVerify(PM, "After Register Allocation");
324 // Perform stack slot coloring.
325 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
326 // FIXME: Re-enable coloring with register when it's capable of adding
328 PM.add(createStackSlotColoringPass(false));
329 printAndVerify(PM, "After StackSlotColoring");
332 // Run post-ra passes.
333 if (addPostRegAlloc(PM, OptLevel))
334 printAndVerify(PM, "After PostRegAlloc passes");
336 PM.add(createLowerSubregsPass());
337 printAndVerify(PM, "After LowerSubregs");
339 // Insert prolog/epilog code. Eliminate abstract frame index references...
340 PM.add(createPrologEpilogCodeInserter());
341 printAndVerify(PM, "After PrologEpilogCodeInserter");
343 // Run pre-sched2 passes.
344 if (addPreSched2(PM, OptLevel))
345 printAndVerify(PM, "After PreSched2 passes");
347 // Second pass scheduler.
348 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
349 PM.add(createPostRAScheduler(OptLevel));
350 printAndVerify(PM, "After PostRAScheduler");
353 // Branch folding must be run after regalloc and prolog/epilog insertion.
354 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
355 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
356 printAndVerify(PM, "After BranchFolding");
360 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
361 PM.add(createTailDuplicatePass(false));
362 printAndVerify(PM, "After TailDuplicate");
365 PM.add(createGCMachineCodeAnalysisPass());
368 PM.add(createGCInfoPrinter(errs()));
370 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
371 PM.add(createCodePlacementOptPass());
372 printAndVerify(PM, "After CodePlacementOpt");
375 if (addPreEmitPass(PM, OptLevel))
376 printAndVerify(PM, "After PreEmit passes");