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/Analysis/Passes.h"
17 #include "llvm/Analysis/Verifier.h"
18 #include "llvm/Assembly/PrintModulePass.h"
19 #include "llvm/CodeGen/AsmPrinter.h"
20 #include "llvm/CodeGen/MachineFunctionAnalysis.h"
21 #include "llvm/CodeGen/MachineModuleInfo.h"
22 #include "llvm/CodeGen/GCStrategy.h"
23 #include "llvm/CodeGen/Passes.h"
24 #include "llvm/Target/TargetLowering.h"
25 #include "llvm/Target/TargetOptions.h"
26 #include "llvm/MC/MCAsmInfo.h"
27 #include "llvm/MC/MCStreamer.h"
28 #include "llvm/Target/TargetAsmInfo.h"
29 #include "llvm/Target/TargetData.h"
30 #include "llvm/Target/TargetRegistry.h"
31 #include "llvm/Transforms/Scalar.h"
32 #include "llvm/ADT/OwningPtr.h"
33 #include "llvm/Support/CommandLine.h"
34 #include "llvm/Support/Debug.h"
35 #include "llvm/Support/FormattedStream.h"
42 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
43 cl::desc("Disable Post Regalloc"));
44 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
45 cl::desc("Disable branch folding"));
46 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
47 cl::desc("Disable tail duplication"));
48 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
49 cl::desc("Disable pre-register allocation tail duplication"));
50 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
51 cl::desc("Disable code placement"));
52 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
53 cl::desc("Disable Stack Slot Coloring"));
54 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
55 cl::desc("Disable Machine LICM"));
56 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
58 cl::desc("Disable Machine LICM"));
59 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
60 cl::desc("Disable Machine Sinking"));
61 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
62 cl::desc("Disable Loop Strength Reduction Pass"));
63 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
64 cl::desc("Disable Codegen Prepare"));
65 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
66 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
67 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
68 cl::desc("Print LLVM IR input to isel pass"));
69 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
70 cl::desc("Dump garbage collector data"));
71 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
72 cl::desc("Show encoding in .s output"));
73 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
74 cl::desc("Show instruction structure in .s output"));
75 static cl::opt<bool> DecodeMCLSDA("decode-mc-lsda", cl::Hidden,
76 cl::desc("Print LSDA in human readable format in .s output"));
77 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
78 cl::desc("Enable MC API logging"));
79 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
80 cl::desc("Verify generated machine code"),
81 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
83 static cl::opt<cl::boolOrDefault>
84 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
85 cl::init(cl::BOU_UNSET));
87 static bool getVerboseAsm() {
90 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
91 case cl::BOU_TRUE: return true;
92 case cl::BOU_FALSE: return false;
96 // Enable or disable FastISel. Both options are needed, because
97 // FastISel is enabled by default with -fast, and we wish to be
98 // able to enable or disable fast-isel independently from -O0.
99 static cl::opt<cl::boolOrDefault>
100 EnableFastISelOption("fast-isel", cl::Hidden,
101 cl::desc("Enable the \"fast\" instruction selector"));
103 LLVMTargetMachine::LLVMTargetMachine(const Target &T,
104 const std::string &Triple)
105 : TargetMachine(T), TargetTriple(Triple) {
106 AsmInfo = T.createAsmInfo(TargetTriple);
109 // Set the default code model for the JIT for a generic target.
110 // FIXME: Is small right here? or .is64Bit() ? Large : Small?
111 void LLVMTargetMachine::setCodeModelForJIT() {
112 setCodeModel(CodeModel::Small);
115 // Set the default code model for static compilation for a generic target.
116 void LLVMTargetMachine::setCodeModelForStatic() {
117 setCodeModel(CodeModel::Small);
120 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
121 formatted_raw_ostream &Out,
122 CodeGenFileType FileType,
123 CodeGenOpt::Level OptLevel,
124 bool DisableVerify) {
125 // Add common CodeGen passes.
126 MCContext *Context = 0;
127 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
129 assert(Context != 0 && "Failed to get MCContext");
131 if (hasMCSaveTempLabels())
132 Context->setAllowTemporaryLabels(false);
134 const MCAsmInfo &MAI = *getMCAsmInfo();
135 OwningPtr<MCStreamer> AsmStreamer;
138 default: return true;
139 case CGFT_AssemblyFile: {
140 MCInstPrinter *InstPrinter =
141 getTarget().createMCInstPrinter(*this, MAI.getAssemblerDialect(), MAI);
143 // Create a code emitter if asked to show the encoding.
144 MCCodeEmitter *MCE = 0;
145 TargetAsmBackend *TAB = 0;
146 if (ShowMCEncoding) {
147 MCE = getTarget().createCodeEmitter(*this, *Context);
148 TAB = getTarget().createAsmBackend(TargetTriple);
151 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
159 AsmStreamer.reset(S);
162 case CGFT_ObjectFile: {
163 // Create the code emitter for the target if it exists. If not, .o file
165 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context);
166 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
167 if (MCE == 0 || TAB == 0)
170 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context,
173 hasMCNoExecStack()));
174 AsmStreamer.get()->InitSections();
178 // The Null output is intended for use for performance analysis and testing,
180 AsmStreamer.reset(createNullStreamer(*Context));
185 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
187 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
188 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
192 // If successful, createAsmPrinter took ownership of AsmStreamer.
197 // Make sure the code model is set.
198 setCodeModelForStatic();
199 PM.add(createGCInfoDeleter());
203 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
204 /// get machine code emitted. This uses a JITCodeEmitter object to handle
205 /// actually outputting the machine code and resolving things like the address
206 /// of functions. This method should returns true if machine code emission is
209 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
211 CodeGenOpt::Level OptLevel,
212 bool DisableVerify) {
213 // Make sure the code model is set.
214 setCodeModelForJIT();
216 // Add common CodeGen passes.
218 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
221 addCodeEmitter(PM, OptLevel, JCE);
222 PM.add(createGCInfoDeleter());
224 return false; // success!
227 /// addPassesToEmitMC - Add passes to the specified pass manager to get
228 /// machine code emitted with the MCJIT. This method returns true if machine
229 /// code is not supported. It fills the MCContext Ctx pointer which can be
230 /// used to build custom MCStreamer.
232 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
235 CodeGenOpt::Level OptLevel,
236 bool DisableVerify) {
237 // Add common CodeGen passes.
238 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
241 if (hasMCSaveTempLabels())
242 Ctx->setAllowTemporaryLabels(false);
244 // Create the code emitter for the target if it exists. If not, .o file
246 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Ctx);
247 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple);
248 if (MCE == 0 || TAB == 0)
251 OwningPtr<MCStreamer> AsmStreamer;
252 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Ctx,
255 hasMCNoExecStack()));
256 AsmStreamer.get()->InitSections();
258 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
259 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
263 // If successful, createAsmPrinter took ownership of AsmStreamer.
268 // Make sure the code model is set.
269 setCodeModelForJIT();
271 return false; // success!
274 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
275 if (PrintMachineCode)
276 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
279 static void printAndVerify(PassManagerBase &PM,
280 const char *Banner) {
281 if (PrintMachineCode)
282 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
284 if (VerifyMachineCode)
285 PM.add(createMachineVerifierPass(Banner));
288 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
289 /// emitting to assembly files or machine code output.
291 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
292 CodeGenOpt::Level OptLevel,
294 MCContext *&OutContext) {
295 // Standard LLVM-Level Passes.
297 // Basic AliasAnalysis support.
298 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
299 // BasicAliasAnalysis wins if they disagree. This is intended to help
300 // support "obvious" type-punning idioms.
301 PM.add(createTypeBasedAliasAnalysisPass());
302 PM.add(createBasicAliasAnalysisPass());
304 // Before running any passes, run the verifier to determine if the input
305 // coming from the front-end and/or optimizer is valid.
307 PM.add(createVerifierPass());
309 // Simplify ObjC ARC code. This is done late because it makes re-optimization
311 PM.add(createObjCARCContractPass());
313 // Run loop strength reduction before anything else.
314 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
315 PM.add(createLoopStrengthReducePass(getTargetLowering()));
317 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
320 PM.add(createGCLoweringPass());
322 // Make sure that no unreachable blocks are instruction selected.
323 PM.add(createUnreachableBlockEliminationPass());
325 // Turn exception handling constructs into something the code generators can
327 switch (getMCAsmInfo()->getExceptionHandlingType()) {
328 case ExceptionHandling::SjLj:
329 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
330 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
331 // catch info can get misplaced when a selector ends up more than one block
332 // removed from the parent invoke(s). This could happen when a landing
333 // pad is shared by multiple invokes and is also a target of a normal
334 // edge from elsewhere.
335 PM.add(createSjLjEHPass(getTargetLowering()));
337 case ExceptionHandling::DwarfCFI:
338 case ExceptionHandling::ARM:
339 case ExceptionHandling::Win64:
340 PM.add(createDwarfEHPass(this));
342 case ExceptionHandling::None:
343 PM.add(createLowerInvokePass(getTargetLowering()));
345 // The lower invoke pass may create unreachable code. Remove it.
346 PM.add(createUnreachableBlockEliminationPass());
350 if (OptLevel != CodeGenOpt::None && !DisableCGP)
351 PM.add(createCodeGenPreparePass(getTargetLowering()));
353 PM.add(createStackProtectorPass(getTargetLowering()));
355 addPreISel(PM, OptLevel);
358 PM.add(createPrintFunctionPass("\n\n"
359 "*** Final LLVM Code input to ISel ***\n",
362 // All passes which modify the LLVM IR are now complete; run the verifier
363 // to ensure that the IR is valid.
365 PM.add(createVerifierPass());
367 // Standard Lower-Level Passes.
369 // Install a MachineModuleInfo class, which is an immutable pass that holds
370 // all the per-module stuff we're generating, including MCContext.
371 TargetAsmInfo *TAI = new TargetAsmInfo(*this);
372 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI);
374 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
376 // Set up a MachineFunction for the rest of CodeGen to work on.
377 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
379 // Enable FastISel with -fast, but allow that to be overridden.
380 if (EnableFastISelOption == cl::BOU_TRUE ||
381 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
382 EnableFastISel = true;
384 // Ask the target for an isel.
385 if (addInstSelector(PM, OptLevel))
388 // Print the instruction selected machine code...
389 printAndVerify(PM, "After Instruction Selection");
391 // Expand pseudo-instructions emitted by ISel.
392 PM.add(createExpandISelPseudosPass());
394 // Optimize PHIs before DCE: removing dead PHI cycles may make more
395 // instructions dead.
396 if (OptLevel != CodeGenOpt::None)
397 PM.add(createOptimizePHIsPass());
399 // If the target requests it, assign local variables to stack slots relative
400 // to one another and simplify frame index references where possible.
401 PM.add(createLocalStackSlotAllocationPass());
403 if (OptLevel != CodeGenOpt::None) {
404 // With optimization, dead code should already be eliminated. However
405 // there is one known exception: lowered code for arguments that are only
406 // used by tail calls, where the tail calls reuse the incoming stack
407 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
408 PM.add(createDeadMachineInstructionElimPass());
409 printAndVerify(PM, "After codegen DCE pass");
411 if (!DisableMachineLICM)
412 PM.add(createMachineLICMPass());
413 PM.add(createMachineCSEPass());
414 if (!DisableMachineSink)
415 PM.add(createMachineSinkingPass());
416 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
418 PM.add(createPeepholeOptimizerPass());
419 printAndVerify(PM, "After codegen peephole optimization pass");
422 // Pre-ra tail duplication.
423 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
424 PM.add(createTailDuplicatePass(true));
425 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
428 // Run pre-ra passes.
429 if (addPreRegAlloc(PM, OptLevel))
430 printAndVerify(PM, "After PreRegAlloc passes");
432 // Perform register allocation.
433 PM.add(createRegisterAllocator(OptLevel));
434 printAndVerify(PM, "After Register Allocation");
436 // Perform stack slot coloring and post-ra machine LICM.
437 if (OptLevel != CodeGenOpt::None) {
438 // FIXME: Re-enable coloring with register when it's capable of adding
441 PM.add(createStackSlotColoringPass(false));
443 // Run post-ra machine LICM to hoist reloads / remats.
444 if (!DisablePostRAMachineLICM)
445 PM.add(createMachineLICMPass(false));
447 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
450 // Run post-ra passes.
451 if (addPostRegAlloc(PM, OptLevel))
452 printAndVerify(PM, "After PostRegAlloc passes");
454 PM.add(createLowerSubregsPass());
455 printAndVerify(PM, "After LowerSubregs");
457 // Insert prolog/epilog code. Eliminate abstract frame index references...
458 PM.add(createPrologEpilogCodeInserter());
459 printAndVerify(PM, "After PrologEpilogCodeInserter");
461 // Run pre-sched2 passes.
462 if (addPreSched2(PM, OptLevel))
463 printAndVerify(PM, "After PreSched2 passes");
465 // Second pass scheduler.
466 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
467 PM.add(createPostRAScheduler(OptLevel));
468 printAndVerify(PM, "After PostRAScheduler");
471 // Branch folding must be run after regalloc and prolog/epilog insertion.
472 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
473 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
474 printNoVerify(PM, "After BranchFolding");
478 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
479 PM.add(createTailDuplicatePass(false));
480 printNoVerify(PM, "After TailDuplicate");
483 PM.add(createGCMachineCodeAnalysisPass());
486 PM.add(createGCInfoPrinter(dbgs()));
488 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
489 PM.add(createCodePlacementOptPass());
490 printNoVerify(PM, "After CodePlacementOpt");
493 if (addPreEmitPass(PM, OptLevel))
494 printNoVerify(PM, "After PreEmit passes");