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);
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);
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 FileModel::Error;
111 case TargetMachine::AssemblyFile:
112 if (addAssemblyEmitter(PM, OptLevel, getAsmVerbosityDefault(), Out))
113 return FileModel::Error;
114 return FileModel::AsmFile;
115 case TargetMachine::ObjectFile:
116 if (getMachOWriterInfo())
117 return FileModel::MachOFile;
118 else if (getELFWriterInfo())
119 return FileModel::ElfFile;
122 return FileModel::Error;
125 bool LLVMTargetMachine::addAssemblyEmitter(PassManagerBase &PM,
126 CodeGenOpt::Level OptLevel,
128 formatted_raw_ostream &Out) {
129 FunctionPass *Printer =
130 getTarget().createAsmPrinter(Out, *this, getMCAsmInfo(), Verbose);
138 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
139 /// be split up (e.g., to add an object writer pass), this method can be used to
140 /// finish up adding passes to emit the file, if necessary.
141 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
142 MachineCodeEmitter *MCE,
143 CodeGenOpt::Level OptLevel) {
144 // Make sure the code model is set.
145 setCodeModelForStatic();
148 addSimpleCodeEmitter(PM, OptLevel, *MCE);
150 addAssemblyEmitter(PM, OptLevel, true, ferrs());
152 PM.add(createGCInfoDeleter());
154 return false; // success!
157 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
158 /// be split up (e.g., to add an object writer pass), this method can be used to
159 /// finish up adding passes to emit the file, if necessary.
160 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
162 CodeGenOpt::Level OptLevel) {
163 // Make sure the code model is set.
164 setCodeModelForJIT();
167 addSimpleCodeEmitter(PM, OptLevel, *JCE);
169 addAssemblyEmitter(PM, OptLevel, true, ferrs());
171 PM.add(createGCInfoDeleter());
173 return false; // success!
176 /// addPassesToEmitFileFinish - If the passes to emit the specified file had to
177 /// be split up (e.g., to add an object writer pass), this method can be used to
178 /// finish up adding passes to emit the file, if necessary.
179 bool LLVMTargetMachine::addPassesToEmitFileFinish(PassManagerBase &PM,
180 ObjectCodeEmitter *OCE,
181 CodeGenOpt::Level OptLevel) {
182 // Make sure the code model is set.
183 setCodeModelForStatic();
186 addSimpleCodeEmitter(PM, OptLevel, *OCE);
188 addAssemblyEmitter(PM, OptLevel, true, ferrs());
190 PM.add(createGCInfoDeleter());
192 return false; // success!
195 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
196 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
197 /// actually outputting the machine code and resolving things like the address
198 /// of functions. This method should returns true if machine code emission is
201 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
202 MachineCodeEmitter &MCE,
203 CodeGenOpt::Level OptLevel) {
204 // Make sure the code model is set.
205 setCodeModelForJIT();
207 // Add common CodeGen passes.
208 if (addCommonCodeGenPasses(PM, OptLevel))
211 addCodeEmitter(PM, OptLevel, MCE);
213 addAssemblyEmitter(PM, OptLevel, true, ferrs());
215 PM.add(createGCInfoDeleter());
217 return false; // success!
220 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
221 /// get machine code emitted. This uses a MachineCodeEmitter object to handle
222 /// actually outputting the machine code and resolving things like the address
223 /// of functions. This method should returns true if machine code emission is
226 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
228 CodeGenOpt::Level OptLevel) {
229 // Make sure the code model is set.
230 setCodeModelForJIT();
232 // Add common CodeGen passes.
233 if (addCommonCodeGenPasses(PM, OptLevel))
236 addCodeEmitter(PM, OptLevel, JCE);
238 addAssemblyEmitter(PM, OptLevel, true, ferrs());
240 PM.add(createGCInfoDeleter());
242 return false; // success!
245 static void printAndVerify(PassManagerBase &PM,
247 bool allowDoubleDefs = false) {
248 if (PrintMachineCode)
249 PM.add(createMachineFunctionPrinterPass(errs(), Banner));
251 if (VerifyMachineCode)
252 PM.add(createMachineVerifierPass(allowDoubleDefs));
255 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
256 /// emitting to assembly files or machine code output.
258 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
259 CodeGenOpt::Level OptLevel) {
260 // Standard LLVM-Level Passes.
262 // Optionally, tun split-GEPs and no-load GVN.
263 if (EnableSplitGEPGVN) {
264 PM.add(createGEPSplitterPass());
265 PM.add(createGVNPass(/*NoPRE=*/false, /*NoLoads=*/true));
268 // Run loop strength reduction before anything else.
269 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
270 PM.add(createLoopStrengthReducePass(getTargetLowering()));
272 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &errs()));
275 // Turn exception handling constructs into something the code generators can
277 switch (getMCAsmInfo()->getExceptionHandlingType())
279 case ExceptionHandling::SjLj:
280 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
281 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
282 PM.add(createSjLjEHPass(getTargetLowering()));
284 case ExceptionHandling::Dwarf:
285 PM.add(createDwarfEHPass(getTargetLowering(), OptLevel==CodeGenOpt::None));
287 case ExceptionHandling::None:
288 PM.add(createLowerInvokePass(getTargetLowering()));
292 PM.add(createGCLoweringPass());
294 // Make sure that no unreachable blocks are instruction selected.
295 PM.add(createUnreachableBlockEliminationPass());
297 if (OptLevel != CodeGenOpt::None && !DisableCGP)
298 PM.add(createCodeGenPreparePass(getTargetLowering()));
300 PM.add(createStackProtectorPass(getTargetLowering()));
303 PM.add(createPrintFunctionPass("\n\n"
304 "*** Final LLVM Code input to ISel ***\n",
307 // Standard Lower-Level Passes.
309 // Set up a MachineFunction for the rest of CodeGen to work on.
310 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
312 // Enable FastISel with -fast, but allow that to be overridden.
313 if (EnableFastISelOption == cl::BOU_TRUE ||
314 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
315 EnableFastISel = true;
317 // Ask the target for an isel.
318 if (addInstSelector(PM, OptLevel))
321 // Print the instruction selected machine code...
322 printAndVerify(PM, "After Instruction Selection",
323 /* allowDoubleDefs= */ true);
325 if (OptLevel != CodeGenOpt::None) {
326 if (!DisableMachineLICM)
327 PM.add(createMachineLICMPass());
328 if (!DisableMachineSink)
329 PM.add(createMachineSinkingPass());
330 printAndVerify(PM, "After MachineLICM and MachineSinking",
331 /* allowDoubleDefs= */ true);
334 // Pre-ra tail duplication.
335 if (OptLevel != CodeGenOpt::None &&
336 !DisableTailDuplicate && PreAllocTailDup) {
337 PM.add(createTailDuplicatePass(true));
338 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
341 // Run pre-ra passes.
342 if (addPreRegAlloc(PM, OptLevel))
343 printAndVerify(PM, "After PreRegAlloc passes",
344 /* allowDoubleDefs= */ true);
346 // Perform register allocation.
347 PM.add(createRegisterAllocator());
348 printAndVerify(PM, "After Register Allocation");
350 // Perform stack slot coloring.
351 if (OptLevel != CodeGenOpt::None && !DisableSSC) {
352 // FIXME: Re-enable coloring with register when it's capable of adding
354 PM.add(createStackSlotColoringPass(false));
355 printAndVerify(PM, "After StackSlotColoring");
358 // Run post-ra passes.
359 if (addPostRegAlloc(PM, OptLevel))
360 printAndVerify(PM, "After PostRegAlloc passes");
362 PM.add(createLowerSubregsPass());
363 printAndVerify(PM, "After LowerSubregs");
365 // Insert prolog/epilog code. Eliminate abstract frame index references...
366 PM.add(createPrologEpilogCodeInserter());
367 printAndVerify(PM, "After PrologEpilogCodeInserter");
369 // Run pre-sched2 passes.
370 if (addPreSched2(PM, OptLevel))
371 printAndVerify(PM, "After PreSched2 passes");
373 // Second pass scheduler.
374 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
375 PM.add(createPostRAScheduler(OptLevel));
376 printAndVerify(PM, "After PostRAScheduler");
379 // Branch folding must be run after regalloc and prolog/epilog insertion.
380 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
381 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
382 printAndVerify(PM, "After BranchFolding");
386 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
387 PM.add(createTailDuplicatePass(false));
388 printAndVerify(PM, "After TailDuplicate");
391 PM.add(createGCMachineCodeAnalysisPass());
394 PM.add(createGCInfoPrinter(errs()));
396 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
397 PM.add(createCodePlacementOptPass());
398 printAndVerify(PM, "After CodePlacementOpt");
401 if (addPreEmitPass(PM, OptLevel))
402 printAndVerify(PM, "After PreEmit passes");