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/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"
36 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
37 cl::desc("Disable Post Regalloc"));
38 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
39 cl::desc("Disable branch folding"));
40 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
41 cl::desc("Disable tail duplication"));
42 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
43 cl::desc("Disable pre-register allocation 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> PrintGCInfo("print-gc", cl::Hidden,
61 cl::desc("Dump garbage collector data"));
62 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
63 cl::desc("Verify generated machine code"),
64 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
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.
70 static cl::opt<cl::boolOrDefault>
71 EnableFastISelOption("fast-isel", cl::Hidden,
72 cl::desc("Enable the \"fast\" instruction selector"));
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.
77 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
78 cl::desc("Split GEPs and run no-load GVN"));
80 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
81 const std::string &TargetTriple)
83 AsmInfo = T.createAsmInfo(TargetTriple);
86 // Set the default code model for the JIT for a generic target.
87 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
89 LLVMTargetMachine::setCodeModelForJIT() {
90 setCodeModel(CodeModel::Small);
93 // Set the default code model for static compilation for a generic target.
95 LLVMTargetMachine::setCodeModelForStatic() {
96 setCodeModel(CodeModel::Small);
99 TargetMachine::CodeGenFileType
100 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
101 formatted_raw_ostream &Out,
102 CodeGenFileType FileType,
103 CodeGenOpt::Level OptLevel) {
104 // Add common CodeGen passes.
105 if (addCommonCodeGenPasses(PM, OptLevel))
106 return CGFT_ErrorOccurred;
110 case CGFT_ObjectFile:
111 return CGFT_ErrorOccurred;
112 case CGFT_AssemblyFile: {
113 FunctionPass *Printer =
114 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(),
115 getAsmVerbosityDefault());
116 if (Printer == 0) return CGFT_ErrorOccurred;
122 // Make sure the code model is set.
123 setCodeModelForStatic();
124 PM.add(createGCInfoDeleter());
128 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
129 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
130 /// actually outputting the machine code and resolving things like the address
131 /// of functions. This method should returns true if machine code emission is
134 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
136 CodeGenOpt::Level OptLevel) {
137 // Make sure the code model is set.
138 setCodeModelForJIT();
140 // Add common CodeGen passes.
141 if (addCommonCodeGenPasses(PM, OptLevel))
144 addCodeEmitter(PM, OptLevel, JCE);
145 PM.add(createGCInfoDeleter());
147 return false; // success!
150 static void printAndVerify(PassManagerBase &PM,
152 bool allowDoubleDefs = false) {
153 if (PrintMachineCode)
154 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
156 if (VerifyMachineCode)
157 PM.add(createMachineVerifierPass(allowDoubleDefs));
160 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
161 /// emitting to assembly files or machine code output.
163 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
164 CodeGenOpt::Level OptLevel) {
165 // Standard LLVM-Level Passes.
167 // Optionally, tun split-GEPs and no-load GVN.
168 if (EnableSplitGEPGVN) {
169 PM.add(createGEPSplitterPass());
170 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
173 // Run loop strength reduction before anything else.
174 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
175 PM.add(createLoopStrengthReducePass(getTargetLowering()));
177 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
180 // Turn exception handling constructs into something the code generators can
182 switch (getMCAsmInfo()->getExceptionHandlingType())
184 case ExceptionHandling::SjLj:
185 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
186 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
187 // catch info can get misplaced when a selector ends up more than one block
188 // removed from the parent invoke(s). This could happen when a landing
189 // pad is shared by multiple invokes and is also a target of a normal
190 // edge from elsewhere.
191 PM.add(createSjLjEHPass(getTargetLowering()));
192 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
194 case ExceptionHandling::Dwarf:
195 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
197 case ExceptionHandling::None:
198 PM.add(createLowerInvokePass(getTargetLowering()));
202 PM.add(createGCLoweringPass());
204 // Make sure that no unreachable blocks are instruction selected.
205 PM.add(createUnreachableBlockEliminationPass());
207 if (OptLevel != CodeGenOpt::None && !DisableCGP)
208 PM.add(createCodeGenPreparePass(getTargetLowering()));
210 PM.add(createStackProtectorPass(getTargetLowering()));
213 PM.add(createPrintFunctionPass("\n\n"
214 "*** Final LLVM Code input to ISel ***\n",
217 // Standard Lower-Level Passes.
219 // Set up a MachineFunction for the rest of CodeGen to work on.
220 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
222 // Enable FastISel with -fast, but allow that to be overridden.
223 if (EnableFastISelOption == cl::BOU_TRUE ||
224 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
225 EnableFastISel = true;
227 // Ask the target for an isel.
228 if (addInstSelector(PM, OptLevel))
231 // Print the instruction selected machine code...
232 printAndVerify(PM, "After Instruction Selection",
233 /* allowDoubleDefs= */ true);
235 if (OptLevel != CodeGenOpt::None) {
236 PM.add(createOptimizeExtsPass());
237 if (!DisableMachineLICM)
238 PM.add(createMachineLICMPass());
239 if (!DisableMachineSink)
240 PM.add(createMachineSinkingPass());
241 printAndVerify(PM, "After MachineLICM and MachineSinking",
242 /* allowDoubleDefs= */ true);
245 // Pre-ra tail duplication.
246 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
247 PM.add(createTailDuplicatePass(true));
248 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
249 /* allowDoubleDefs= */ true);
252 // Run pre-ra passes.
253 if (addPreRegAlloc(PM, OptLevel))
254 printAndVerify(PM, "After PreRegAlloc passes",
255 /* allowDoubleDefs= */ true);
257 // Perform register allocation.
258 PM.add(createRegisterAllocator());
259 printAndVerify(PM, "After Register Allocation");
261 // Perform stack slot coloring.
262 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
263 // FIXME: Re-enable coloring with register when it's capable of adding
265 PM.add(createStackSlotColoringPass(false));
266 printAndVerify(PM, "After StackSlotColoring");
269 // Run post-ra passes.
270 if (addPostRegAlloc(PM, OptLevel))
271 printAndVerify(PM, "After PostRegAlloc passes");
273 PM.add(createLowerSubregsPass());
274 printAndVerify(PM, "After LowerSubregs");
276 // Insert prolog/epilog code. Eliminate abstract frame index references...
277 PM.add(createPrologEpilogCodeInserter());
278 printAndVerify(PM, "After PrologEpilogCodeInserter");
280 // Run pre-sched2 passes.
281 if (addPreSched2(PM, OptLevel))
282 printAndVerify(PM, "After PreSched2 passes");
284 // Second pass scheduler.
285 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
286 PM.add(createPostRAScheduler(OptLevel));
287 printAndVerify(PM, "After PostRAScheduler");
290 // Branch folding must be run after regalloc and prolog/epilog insertion.
291 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
292 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
293 printAndVerify(PM, "After BranchFolding");
297 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
298 PM.add(createTailDuplicatePass(false));
299 printAndVerify(PM, "After TailDuplicate");
302 PM.add(createGCMachineCodeAnalysisPass());
305 PM.add(createGCInfoPrinter(dbgs()));
307 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
308 PM.add(createCodePlacementOptPass());
309 printAndVerify(PM, "After CodePlacementOpt");
312 if (addPreEmitPass(PM, OptLevel))
313 printAndVerify(PM, "After PreEmit passes");