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/Debug.h"
28 #include "llvm/Support/FormattedStream.h"
35 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
36 cl::desc("Disable Post Regalloc"));
37 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
38 cl::desc("Disable branch folding"));
39 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
40 cl::desc("Disable tail duplication"));
41 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
42 cl::desc("Disable pre-register allocation tail duplication"));
43 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
44 cl::desc("Disable code placement"));
45 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
46 cl::desc("Disable Stack Slot Coloring"));
47 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
48 cl::desc("Disable Machine LICM"));
49 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
50 cl::desc("Disable Machine Sinking"));
51 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
52 cl::desc("Disable Loop Strength Reduction Pass"));
53 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
54 cl::desc("Disable Codegen Prepare"));
55 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
56 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
57 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
58 cl::desc("Print LLVM IR input to isel pass"));
59 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
60 cl::desc("Dump garbage collector data"));
61 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
62 cl::desc("Verify generated machine code"),
63 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
65 static cl::opt<cl::boolOrDefault>
66 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
67 cl::init(cl::BOU_UNSET));
69 static bool getVerboseAsm() {
72 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
73 case cl::BOU_TRUE: return true;
74 case cl::BOU_FALSE: return false;
78 // Enable or disable FastISel. Both options are needed, because
79 // FastISel is enabled by default with -fast, and we wish to be
80 // able to enable or disable fast-isel independently from -O0.
81 static cl::opt<cl::boolOrDefault>
82 EnableFastISelOption("fast-isel", cl::Hidden,
83 cl::desc("Enable the \"fast\" instruction selector"));
85 // Enable or disable an experimental optimization to split GEPs
86 // and run a special GVN pass which does not examine loads, in
87 // an effort to factor out redundancy implicit in complex GEPs.
88 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
89 cl::desc("Split GEPs and run no-load GVN"));
91 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
92 const std::string &TargetTriple)
94 AsmInfo = T.createAsmInfo(TargetTriple);
97 // Set the default code model for the JIT for a generic target.
98 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
100 LLVMTargetMachine::setCodeModelForJIT() {
101 setCodeModel(CodeModel::Small);
104 // Set the default code model for static compilation for a generic target.
106 LLVMTargetMachine::setCodeModelForStatic() {
107 setCodeModel(CodeModel::Small);
110 TargetMachine::CodeGenFileType
111 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
112 formatted_raw_ostream &Out,
113 CodeGenFileType FileType,
114 CodeGenOpt::Level OptLevel) {
115 // Add common CodeGen passes.
116 if (addCommonCodeGenPasses(PM, OptLevel))
117 return CGFT_ErrorOccurred;
121 case CGFT_ObjectFile:
122 return CGFT_ErrorOccurred;
123 case CGFT_AssemblyFile: {
124 FunctionPass *Printer =
125 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(),
127 if (Printer == 0) return CGFT_ErrorOccurred;
133 // Make sure the code model is set.
134 setCodeModelForStatic();
135 PM.add(createGCInfoDeleter());
139 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
140 /// get machine code emitted. This uses a JITCodeEmitter object to handle
141 /// actually outputting the machine code and resolving things like the address
142 /// of functions. This method should returns true if machine code emission is
145 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
147 CodeGenOpt::Level OptLevel) {
148 // Make sure the code model is set.
149 setCodeModelForJIT();
151 // Add common CodeGen passes.
152 if (addCommonCodeGenPasses(PM, OptLevel))
155 addCodeEmitter(PM, OptLevel, JCE);
156 PM.add(createGCInfoDeleter());
158 return false; // success!
161 static void printAndVerify(PassManagerBase &PM,
163 bool allowDoubleDefs = false) {
164 if (PrintMachineCode)
165 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
167 if (VerifyMachineCode)
168 PM.add(createMachineVerifierPass(allowDoubleDefs));
171 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
172 /// emitting to assembly files or machine code output.
174 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
175 CodeGenOpt::Level OptLevel) {
176 // Standard LLVM-Level Passes.
178 // Optionally, tun split-GEPs and no-load GVN.
179 if (EnableSplitGEPGVN) {
180 PM.add(createGEPSplitterPass());
181 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
184 // Run loop strength reduction before anything else.
185 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
186 PM.add(createLoopStrengthReducePass(getTargetLowering()));
188 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
191 // Turn exception handling constructs into something the code generators can
193 switch (getMCAsmInfo()->getExceptionHandlingType())
195 case ExceptionHandling::SjLj:
196 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
197 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
198 // catch info can get misplaced when a selector ends up more than one block
199 // removed from the parent invoke(s). This could happen when a landing
200 // pad is shared by multiple invokes and is also a target of a normal
201 // edge from elsewhere.
202 PM.add(createSjLjEHPass(getTargetLowering()));
203 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
205 case ExceptionHandling::Dwarf:
206 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
208 case ExceptionHandling::None:
209 PM.add(createLowerInvokePass(getTargetLowering()));
213 PM.add(createGCLoweringPass());
215 // Make sure that no unreachable blocks are instruction selected.
216 PM.add(createUnreachableBlockEliminationPass());
218 if (OptLevel != CodeGenOpt::None && !DisableCGP)
219 PM.add(createCodeGenPreparePass(getTargetLowering()));
221 PM.add(createStackProtectorPass(getTargetLowering()));
224 PM.add(createPrintFunctionPass("\n\n"
225 "*** Final LLVM Code input to ISel ***\n",
228 // Standard Lower-Level Passes.
230 // Set up a MachineFunction for the rest of CodeGen to work on.
231 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
233 // Enable FastISel with -fast, but allow that to be overridden.
234 if (EnableFastISelOption == cl::BOU_TRUE ||
235 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
236 EnableFastISel = true;
238 // Ask the target for an isel.
239 if (addInstSelector(PM, OptLevel))
242 // Print the instruction selected machine code...
243 printAndVerify(PM, "After Instruction Selection",
244 /* allowDoubleDefs= */ true);
246 if (OptLevel != CodeGenOpt::None) {
247 PM.add(createOptimizeExtsPass());
248 if (!DisableMachineLICM)
249 PM.add(createMachineLICMPass());
250 if (!DisableMachineSink)
251 PM.add(createMachineSinkingPass());
252 printAndVerify(PM, "After MachineLICM and MachineSinking",
253 /* allowDoubleDefs= */ true);
256 // Pre-ra tail duplication.
257 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
258 PM.add(createTailDuplicatePass(true));
259 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
260 /* allowDoubleDefs= */ true);
263 // Run pre-ra passes.
264 if (addPreRegAlloc(PM, OptLevel))
265 printAndVerify(PM, "After PreRegAlloc passes",
266 /* allowDoubleDefs= */ true);
268 // Perform register allocation.
269 PM.add(createRegisterAllocator());
270 printAndVerify(PM, "After Register Allocation");
272 // Perform stack slot coloring.
273 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
274 // FIXME: Re-enable coloring with register when it's capable of adding
276 PM.add(createStackSlotColoringPass(false));
277 printAndVerify(PM, "After StackSlotColoring");
280 // Run post-ra passes.
281 if (addPostRegAlloc(PM, OptLevel))
282 printAndVerify(PM, "After PostRegAlloc passes");
284 PM.add(createLowerSubregsPass());
285 printAndVerify(PM, "After LowerSubregs");
287 // Insert prolog/epilog code. Eliminate abstract frame index references...
288 PM.add(createPrologEpilogCodeInserter());
289 printAndVerify(PM, "After PrologEpilogCodeInserter");
291 // Run pre-sched2 passes.
292 if (addPreSched2(PM, OptLevel))
293 printAndVerify(PM, "After PreSched2 passes");
295 // Second pass scheduler.
296 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
297 PM.add(createPostRAScheduler(OptLevel));
298 printAndVerify(PM, "After PostRAScheduler");
301 // Branch folding must be run after regalloc and prolog/epilog insertion.
302 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
303 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
304 printAndVerify(PM, "After BranchFolding");
308 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
309 PM.add(createTailDuplicatePass(false));
310 printAndVerify(PM, "After TailDuplicate");
313 PM.add(createGCMachineCodeAnalysisPass());
316 PM.add(createGCInfoPrinter(dbgs()));
318 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
319 PM.add(createCodePlacementOptPass());
320 printAndVerify(PM, "After CodePlacementOpt");
323 if (addPreEmitPass(PM, OptLevel))
324 printAndVerify(PM, "After PreEmit passes");