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> 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));
69 // Enable or disable FastISel. Both options are needed, because
70 // FastISel is enabled by default with -fast, and we wish to be
71 // able to enable or disable fast-isel independently from -O0.
72 static cl::opt<cl::boolOrDefault>
73 EnableFastISelOption("fast-isel", cl::Hidden,
74 cl::desc("Enable the \"fast\" instruction selector"));
76 // Enable or disable an experimental optimization to split GEPs
77 // and run a special GVN pass which does not examine loads, in
78 // an effort to factor out redundancy implicit in complex GEPs.
79 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden,
80 cl::desc("Split GEPs and run no-load GVN"));
82 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
83 const std::string &TargetTriple)
85 AsmInfo = T.createAsmInfo(TargetTriple);
88 // Set the default code model for the JIT for a generic target.
89 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
91 LLVMTargetMachine::setCodeModelForJIT() {
92 setCodeModel(CodeModel::Small);
95 // Set the default code model for static compilation for a generic target.
97 LLVMTargetMachine::setCodeModelForStatic() {
98 setCodeModel(CodeModel::Small);
102 LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
103 formatted_raw_ostream &Out,
104 CodeGenFileType FileType,
105 CodeGenOpt::Level OptLevel) {
106 // Add common CodeGen passes.
107 if (addCommonCodeGenPasses(PM, OptLevel))
108 return FileModel::Error;
113 case TargetMachine::AssemblyFile:
114 if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
115 return FileModel::Error;
116 return FileModel::AsmFile;
117 case TargetMachine::ObjectFile:
118 return FileModel::Error;
120 return FileModel::Error;
123 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
124 CodeGenOpt::Level OptLevel,
126 formatted_raw_ostream &Out) {
127 FunctionPass *Printer =
128 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
136 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
137 /// be split up (e.g., to add an object writer pass), this method can be used to
138 /// finish up adding passes to emit the file, if necessary.
139 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
140 MachineCodeEmitter *MCE,
141 CodeGenOpt::Level OptLevel) {
142 // Make sure the code model is set.
143 setCodeModelForStatic();
146 addSimpleCodeEmitter(PM, OptLevel, *MCE);
148 addAssemblyEmitter(PM, OptLevel, true, ferrs());
150 PM.add(createGCInfoDeleter());
152 return false; // success!
155 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
156 /// be split up (e.g., to add an object writer pass), this method can be used to
157 /// finish up adding passes to emit the file, if necessary.
158 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
160 CodeGenOpt::Level OptLevel) {
161 // Make sure the code model is set.
162 setCodeModelForJIT();
165 addSimpleCodeEmitter(PM, OptLevel, *JCE);
167 addAssemblyEmitter(PM, OptLevel, true, ferrs());
169 PM.add(createGCInfoDeleter());
171 return false; // success!
174 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
175 /// be split up (e.g., to add an object writer pass), this method can be used to
176 /// finish up adding passes to emit the file, if necessary.
177 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
178 ObjectCodeEmitter *OCE,
179 CodeGenOpt::Level OptLevel) {
180 // Make sure the code model is set.
181 setCodeModelForStatic();
184 addAssemblyEmitter(PM, OptLevel, true, ferrs());
186 PM.add(createGCInfoDeleter());
188 return false; // success!
191 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
192 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
193 /// actually outputting the machine code and resolving things like the address
194 /// of functions. This method should returns true if machine code emission is
197 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
198 MachineCodeEmitter &MCE,
199 CodeGenOpt::Level OptLevel) {
200 // Make sure the code model is set.
201 setCodeModelForJIT();
203 // Add common CodeGen passes.
204 if (addCommonCodeGenPasses(PM, OptLevel))
207 addCodeEmitter(PM, OptLevel, MCE);
209 addAssemblyEmitter(PM, OptLevel, true, ferrs());
211 PM.add(createGCInfoDeleter());
213 return false; // success!
216 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
217 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
218 /// actually outputting the machine code and resolving things like the address
219 /// of functions. This method should returns true if machine code emission is
222 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
224 CodeGenOpt::Level OptLevel) {
225 // Make sure the code model is set.
226 setCodeModelForJIT();
228 // Add common CodeGen passes.
229 if (addCommonCodeGenPasses(PM, OptLevel))
232 addCodeEmitter(PM, OptLevel, JCE);
234 addAssemblyEmitter(PM, OptLevel, true, ferrs());
236 PM.add(createGCInfoDeleter());
238 return false; // success!
241 static void printAndVerify(PassManagerBase &PM,
243 bool allowDoubleDefs = false) {
244 if (PrintMachineCode)
245 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
247 if (VerifyMachineCode)
248 PM.add(createMachineVerifierPass(allowDoubleDefs));
251 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
252 /// emitting to assembly files or machine code output.
254 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
255 CodeGenOpt::Level OptLevel) {
256 // Standard LLVM-Level Passes.
258 // Optionally, tun split-GEPs and no-load GVN.
259 if (EnableSplitGEPGVN) {
260 PM.add(createGEPSplitterPass());
261 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
264 // Run loop strength reduction before anything else.
265 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
266 PM.add(createLoopStrengthReducePass(getTargetLowering()));
268 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
271 // Turn exception handling constructs into something the code generators can
273 switch (getMCAsmInfo()->getExceptionHandlingType())
275 case ExceptionHandling::SjLj:
276 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
277 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
278 // catch info can get misplaced when a selector ends up more than one block
279 // removed from the parent invoke(s). This could happen when a landing
280 // pad is shared by multiple invokes and is also a target of a normal
281 // edge from elsewhere.
282 PM.add(createSjLjEHPass(getTargetLowering()));
283 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
285 case ExceptionHandling::Dwarf:
286 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
288 case ExceptionHandling::None:
289 PM.add(createLowerInvokePass(getTargetLowering()));
293 PM.add(createGCLoweringPass());
295 // Make sure that no unreachable blocks are instruction selected.
296 PM.add(createUnreachableBlockEliminationPass());
298 if (OptLevel != CodeGenOpt::None && !DisableCGP)
299 PM.add(createCodeGenPreparePass(getTargetLowering()));
301 PM.add(createStackProtectorPass(getTargetLowering()));
304 PM.add(createPrintFunctionPass("\n\n"
305 "*** Final LLVM Code input to ISel ***\n",
308 // Standard Lower-Level Passes.
310 // Set up a MachineFunction for the rest of CodeGen to work on.
311 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
313 // Enable FastISel with -fast, but allow that to be overridden.
314 if (EnableFastISelOption == cl::BOU_TRUE ||
315 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
316 EnableFastISel = true;
318 // Ask the target for an isel.
319 if (addInstSelector(PM, OptLevel))
322 // Print the instruction selected machine code...
323 printAndVerify(PM, "After Instruction Selection",
324 /* allowDoubleDefs= */ true);
326 if (OptLevel != CodeGenOpt::None) {
327 PM.add(createOptimizeExtsPass());
328 if (!DisableMachineLICM)
329 PM.add(createMachineLICMPass());
330 if (!DisableMachineSink)
331 PM.add(createMachineSinkingPass());
332 printAndVerify(PM, "After MachineLICM and MachineSinking",
333 /* allowDoubleDefs= */ true);
336 // Pre-ra tail duplication.
337 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
338 PM.add(createTailDuplicatePass(true));
339 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate",
340 /* allowDoubleDefs= */ true);
343 // Run pre-ra passes.
344 if (addPreRegAlloc(PM, OptLevel))
345 printAndVerify(PM, "After PreRegAlloc passes",
346 /* allowDoubleDefs= */ true);
348 // Perform register allocation.
349 PM.add(createRegisterAllocator());
350 printAndVerify(PM, "After Register Allocation");
352 // Perform stack slot coloring.
353 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
354 // FIXME: Re-enable coloring with register when it's capable of adding
356 PM.add(createStackSlotColoringPass(false));
357 printAndVerify(PM, "After StackSlotColoring");
360 // Run post-ra passes.
361 if (addPostRegAlloc(PM, OptLevel))
362 printAndVerify(PM, "After PostRegAlloc passes");
364 PM.add(createLowerSubregsPass());
365 printAndVerify(PM, "After LowerSubregs");
367 // Insert prolog/epilog code. Eliminate abstract frame index references...
368 PM.add(createPrologEpilogCodeInserter());
369 printAndVerify(PM, "After PrologEpilogCodeInserter");
371 // Run pre-sched2 passes.
372 if (addPreSched2(PM, OptLevel))
373 printAndVerify(PM, "After PreSched2 passes");
375 // Second pass scheduler.
376 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
377 PM.add(createPostRAScheduler(OptLevel));
378 printAndVerify(PM, "After PostRAScheduler");
381 // Branch folding must be run after regalloc and prolog/epilog insertion.
382 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
383 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
384 printAndVerify(PM, "After BranchFolding");
388 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
389 PM.add(createTailDuplicatePass(false));
390 printAndVerify(PM, "After TailDuplicate");
393 PM.add(createGCMachineCodeAnalysisPass());
396 PM.add(createGCInfoPrinter(dbgs()));
398 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
399 PM.add(createCodePlacementOptPass());
400 printAndVerify(PM, "After CodePlacementOpt");
403 if (addPreEmitPass(PM, OptLevel))
404 printAndVerify(PM, "After PreEmit passes");