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/MCInstrInfo.h"
28 #include "llvm/MC/MCStreamer.h"
29 #include "llvm/MC/MCSubtargetInfo.h"
30 #include "llvm/Target/TargetData.h"
31 #include "llvm/Target/TargetInstrInfo.h"
32 #include "llvm/Target/TargetLowering.h"
33 #include "llvm/Target/TargetLoweringObjectFile.h"
34 #include "llvm/Target/TargetRegisterInfo.h"
35 #include "llvm/Target/TargetRegistry.h"
36 #include "llvm/Target/TargetSubtargetInfo.h"
37 #include "llvm/Transforms/Scalar.h"
38 #include "llvm/ADT/OwningPtr.h"
39 #include "llvm/Support/CommandLine.h"
40 #include "llvm/Support/Debug.h"
41 #include "llvm/Support/FormattedStream.h"
48 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
49 cl::desc("Disable Post Regalloc"));
50 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
51 cl::desc("Disable branch folding"));
52 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
53 cl::desc("Disable tail duplication"));
54 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
55 cl::desc("Disable pre-register allocation tail duplication"));
56 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
57 cl::desc("Disable code placement"));
58 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
59 cl::desc("Disable Stack Slot Coloring"));
60 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
61 cl::desc("Disable Machine LICM"));
62 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
64 cl::desc("Disable Machine LICM"));
65 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
66 cl::desc("Disable Machine Sinking"));
67 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
68 cl::desc("Disable Loop Strength Reduction Pass"));
69 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
70 cl::desc("Disable Codegen Prepare"));
71 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
72 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
73 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
74 cl::desc("Print LLVM IR input to isel pass"));
75 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
76 cl::desc("Dump garbage collector data"));
77 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
78 cl::desc("Show encoding in .s output"));
79 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
80 cl::desc("Show instruction structure in .s output"));
81 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
82 cl::desc("Enable MC API logging"));
83 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
84 cl::desc("Verify generated machine code"),
85 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
87 static cl::opt<cl::boolOrDefault>
88 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
89 cl::init(cl::BOU_UNSET));
91 static bool getVerboseAsm() {
94 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
95 case cl::BOU_TRUE: return true;
96 case cl::BOU_FALSE: return false;
100 // Enable or disable FastISel. Both options are needed, because
101 // FastISel is enabled by default with -fast, and we wish to be
102 // able to enable or disable fast-isel independently from -O0.
103 static cl::opt<cl::boolOrDefault>
104 EnableFastISelOption("fast-isel", cl::Hidden,
105 cl::desc("Enable the \"fast\" instruction selector"));
107 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
108 StringRef CPU, StringRef FS,
109 Reloc::Model RM, CodeModel::Model CM)
110 : TargetMachine(T, Triple, CPU, FS) {
111 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM);
112 AsmInfo = T.createMCAsmInfo(Triple);
115 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
116 formatted_raw_ostream &Out,
117 CodeGenFileType FileType,
118 CodeGenOpt::Level OptLevel,
119 bool DisableVerify) {
120 // Add common CodeGen passes.
121 MCContext *Context = 0;
122 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
124 assert(Context != 0 && "Failed to get MCContext");
126 if (hasMCSaveTempLabels())
127 Context->setAllowTemporaryLabels(false);
129 const MCAsmInfo &MAI = *getMCAsmInfo();
130 OwningPtr<MCStreamer> AsmStreamer;
133 default: return true;
134 case CGFT_AssemblyFile: {
135 MCInstPrinter *InstPrinter =
136 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI);
138 // Create a code emitter if asked to show the encoding.
139 MCCodeEmitter *MCE = 0;
140 MCAsmBackend *MAB = 0;
141 if (ShowMCEncoding) {
142 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
143 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
144 MAB = getTarget().createMCAsmBackend(getTargetTriple());
147 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
154 AsmStreamer.reset(S);
157 case CGFT_ObjectFile: {
158 // Create the code emitter for the target if it exists. If not, .o file
160 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
161 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
163 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
164 if (MCE == 0 || MAB == 0)
167 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
169 MCE, hasMCRelaxAll(),
170 hasMCNoExecStack()));
171 AsmStreamer.get()->InitSections();
175 // The Null output is intended for use for performance analysis and testing,
177 AsmStreamer.reset(createNullStreamer(*Context));
182 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
184 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
185 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
189 // If successful, createAsmPrinter took ownership of AsmStreamer.
194 PM.add(createGCInfoDeleter());
198 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
199 /// get machine code emitted. This uses a JITCodeEmitter object to handle
200 /// actually outputting the machine code and resolving things like the address
201 /// of functions. This method should returns true if machine code emission is
204 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
206 CodeGenOpt::Level OptLevel,
207 bool DisableVerify) {
208 // Add common CodeGen passes.
210 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
213 addCodeEmitter(PM, OptLevel, JCE);
214 PM.add(createGCInfoDeleter());
216 return false; // success!
219 /// addPassesToEmitMC - Add passes to the specified pass manager to get
220 /// machine code emitted with the MCJIT. This method returns true if machine
221 /// code is not supported. It fills the MCContext Ctx pointer which can be
222 /// used to build custom MCStreamer.
224 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
227 CodeGenOpt::Level OptLevel,
228 bool DisableVerify) {
229 // Add common CodeGen passes.
230 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
233 if (hasMCSaveTempLabels())
234 Ctx->setAllowTemporaryLabels(false);
236 // Create the code emitter for the target if it exists. If not, .o file
238 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
239 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
240 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
241 if (MCE == 0 || MAB == 0)
244 OwningPtr<MCStreamer> AsmStreamer;
245 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
248 hasMCNoExecStack()));
249 AsmStreamer.get()->InitSections();
251 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
252 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
256 // If successful, createAsmPrinter took ownership of AsmStreamer.
261 return false; // success!
264 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
265 if (PrintMachineCode)
266 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
269 static void printAndVerify(PassManagerBase &PM,
270 const char *Banner) {
271 if (PrintMachineCode)
272 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
274 if (VerifyMachineCode)
275 PM.add(createMachineVerifierPass(Banner));
278 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
279 /// emitting to assembly files or machine code output.
281 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
282 CodeGenOpt::Level OptLevel,
284 MCContext *&OutContext) {
285 // Standard LLVM-Level Passes.
287 // Basic AliasAnalysis support.
288 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
289 // BasicAliasAnalysis wins if they disagree. This is intended to help
290 // support "obvious" type-punning idioms.
291 PM.add(createTypeBasedAliasAnalysisPass());
292 PM.add(createBasicAliasAnalysisPass());
294 // Before running any passes, run the verifier to determine if the input
295 // coming from the front-end and/or optimizer is valid.
297 PM.add(createVerifierPass());
299 // Run loop strength reduction before anything else.
300 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
301 PM.add(createLoopStrengthReducePass(getTargetLowering()));
303 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
306 PM.add(createGCLoweringPass());
308 // Make sure that no unreachable blocks are instruction selected.
309 PM.add(createUnreachableBlockEliminationPass());
311 // Turn exception handling constructs into something the code generators can
313 switch (getMCAsmInfo()->getExceptionHandlingType()) {
314 case ExceptionHandling::SjLj:
315 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
316 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
317 // catch info can get misplaced when a selector ends up more than one block
318 // removed from the parent invoke(s). This could happen when a landing
319 // pad is shared by multiple invokes and is also a target of a normal
320 // edge from elsewhere.
321 PM.add(createSjLjEHPass(getTargetLowering()));
323 case ExceptionHandling::DwarfCFI:
324 case ExceptionHandling::ARM:
325 case ExceptionHandling::Win64:
326 PM.add(createDwarfEHPass(this));
328 case ExceptionHandling::None:
329 PM.add(createLowerInvokePass(getTargetLowering()));
331 // The lower invoke pass may create unreachable code. Remove it.
332 PM.add(createUnreachableBlockEliminationPass());
336 if (OptLevel != CodeGenOpt::None && !DisableCGP)
337 PM.add(createCodeGenPreparePass(getTargetLowering()));
339 PM.add(createStackProtectorPass(getTargetLowering()));
341 addPreISel(PM, OptLevel);
344 PM.add(createPrintFunctionPass("\n\n"
345 "*** Final LLVM Code input to ISel ***\n",
348 // All passes which modify the LLVM IR are now complete; run the verifier
349 // to ensure that the IR is valid.
351 PM.add(createVerifierPass());
353 // Standard Lower-Level Passes.
355 // Install a MachineModuleInfo class, which is an immutable pass that holds
356 // all the per-module stuff we're generating, including MCContext.
357 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
359 &getTargetLowering()->getObjFileLowering());
361 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
363 // Set up a MachineFunction for the rest of CodeGen to work on.
364 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
366 // Enable FastISel with -fast, but allow that to be overridden.
367 if (EnableFastISelOption == cl::BOU_TRUE ||
368 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
369 EnableFastISel = true;
371 // Ask the target for an isel.
372 if (addInstSelector(PM, OptLevel))
375 // Print the instruction selected machine code...
376 printAndVerify(PM, "After Instruction Selection");
378 // Expand pseudo-instructions emitted by ISel.
379 PM.add(createExpandISelPseudosPass());
381 // Pre-ra tail duplication.
382 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
383 PM.add(createTailDuplicatePass(true));
384 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
387 // Optimize PHIs before DCE: removing dead PHI cycles may make more
388 // instructions dead.
389 if (OptLevel != CodeGenOpt::None)
390 PM.add(createOptimizePHIsPass());
392 // If the target requests it, assign local variables to stack slots relative
393 // to one another and simplify frame index references where possible.
394 PM.add(createLocalStackSlotAllocationPass());
396 if (OptLevel != CodeGenOpt::None) {
397 // With optimization, dead code should already be eliminated. However
398 // there is one known exception: lowered code for arguments that are only
399 // used by tail calls, where the tail calls reuse the incoming stack
400 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
401 PM.add(createDeadMachineInstructionElimPass());
402 printAndVerify(PM, "After codegen DCE pass");
404 if (!DisableMachineLICM)
405 PM.add(createMachineLICMPass());
406 PM.add(createMachineCSEPass());
407 if (!DisableMachineSink)
408 PM.add(createMachineSinkingPass());
409 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
411 PM.add(createPeepholeOptimizerPass());
412 printAndVerify(PM, "After codegen peephole optimization pass");
415 // Run pre-ra passes.
416 if (addPreRegAlloc(PM, OptLevel))
417 printAndVerify(PM, "After PreRegAlloc passes");
419 // Perform register allocation.
420 PM.add(createRegisterAllocator(OptLevel));
421 printAndVerify(PM, "After Register Allocation");
423 // Perform stack slot coloring and post-ra machine LICM.
424 if (OptLevel != CodeGenOpt::None) {
425 // FIXME: Re-enable coloring with register when it's capable of adding
428 PM.add(createStackSlotColoringPass(false));
430 // Run post-ra machine LICM to hoist reloads / remats.
431 if (!DisablePostRAMachineLICM)
432 PM.add(createMachineLICMPass(false));
434 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
437 // Run post-ra passes.
438 if (addPostRegAlloc(PM, OptLevel))
439 printAndVerify(PM, "After PostRegAlloc passes");
441 PM.add(createLowerSubregsPass());
442 printAndVerify(PM, "After LowerSubregs");
444 // Insert prolog/epilog code. Eliminate abstract frame index references...
445 PM.add(createPrologEpilogCodeInserter());
446 printAndVerify(PM, "After PrologEpilogCodeInserter");
448 // Run pre-sched2 passes.
449 if (addPreSched2(PM, OptLevel))
450 printAndVerify(PM, "After PreSched2 passes");
452 // Second pass scheduler.
453 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
454 PM.add(createPostRAScheduler(OptLevel));
455 printAndVerify(PM, "After PostRAScheduler");
458 // Branch folding must be run after regalloc and prolog/epilog insertion.
459 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
460 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
461 printNoVerify(PM, "After BranchFolding");
465 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
466 PM.add(createTailDuplicatePass(false));
467 printNoVerify(PM, "After TailDuplicate");
470 PM.add(createGCMachineCodeAnalysisPass());
473 PM.add(createGCInfoPrinter(dbgs()));
475 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
476 PM.add(createCodePlacementOptPass());
477 printNoVerify(PM, "After CodePlacementOpt");
480 if (addPreEmitPass(PM, OptLevel))
481 printNoVerify(PM, "After PreEmit passes");