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/TargetSubtargetInfo.h"
36 #include "llvm/Transforms/Scalar.h"
37 #include "llvm/ADT/OwningPtr.h"
38 #include "llvm/Support/CommandLine.h"
39 #include "llvm/Support/Debug.h"
40 #include "llvm/Support/FormattedStream.h"
41 #include "llvm/Support/TargetRegistry.h"
48 static cl::opt<bool> DisableOldSjLjEH("disable-old-sjlj-eh", cl::Hidden,
49 cl::desc("Disable the old SjLj EH preparation pass"));
51 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
52 cl::desc("Disable Post Regalloc"));
53 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
54 cl::desc("Disable branch folding"));
55 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
56 cl::desc("Disable tail duplication"));
57 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
58 cl::desc("Disable pre-register allocation tail duplication"));
59 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden,
60 cl::desc("Disable code placement"));
61 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden,
62 cl::desc("Disable Stack Slot Coloring"));
63 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden,
64 cl::desc("Disable Machine Dead Code Elimination"));
65 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
66 cl::desc("Disable Machine LICM"));
67 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
68 cl::desc("Disable Machine Common Subexpression Elimination"));
69 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
71 cl::desc("Disable Machine LICM"));
72 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
73 cl::desc("Disable Machine Sinking"));
74 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
75 cl::desc("Disable Loop Strength Reduction Pass"));
76 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
77 cl::desc("Disable Codegen Prepare"));
78 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
79 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
80 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
81 cl::desc("Print LLVM IR input to isel pass"));
82 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
83 cl::desc("Dump garbage collector data"));
84 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
85 cl::desc("Show encoding in .s output"));
86 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
87 cl::desc("Show instruction structure in .s output"));
88 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
89 cl::desc("Enable MC API logging"));
90 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
91 cl::desc("Verify generated machine code"),
92 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
94 static cl::opt<cl::boolOrDefault>
95 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
96 cl::init(cl::BOU_UNSET));
98 static bool getVerboseAsm() {
101 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
102 case cl::BOU_TRUE: return true;
103 case cl::BOU_FALSE: return false;
107 // Enable or disable FastISel. Both options are needed, because
108 // FastISel is enabled by default with -fast, and we wish to be
109 // able to enable or disable fast-isel independently from -O0.
110 static cl::opt<cl::boolOrDefault>
111 EnableFastISelOption("fast-isel", cl::Hidden,
112 cl::desc("Enable the \"fast\" instruction selector"));
114 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
115 StringRef CPU, StringRef FS,
116 Reloc::Model RM, CodeModel::Model CM)
117 : TargetMachine(T, Triple, CPU, FS) {
118 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM);
119 AsmInfo = T.createMCAsmInfo(Triple);
122 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
123 formatted_raw_ostream &Out,
124 CodeGenFileType FileType,
125 CodeGenOpt::Level OptLevel,
126 bool DisableVerify) {
127 // Add common CodeGen passes.
128 MCContext *Context = 0;
129 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
131 assert(Context != 0 && "Failed to get MCContext");
133 if (hasMCSaveTempLabels())
134 Context->setAllowTemporaryLabels(false);
136 const MCAsmInfo &MAI = *getMCAsmInfo();
137 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
138 OwningPtr<MCStreamer> AsmStreamer;
141 default: return true;
142 case CGFT_AssemblyFile: {
143 MCInstPrinter *InstPrinter =
144 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
146 // Create a code emitter if asked to show the encoding.
147 MCCodeEmitter *MCE = 0;
148 MCAsmBackend *MAB = 0;
149 if (ShowMCEncoding) {
150 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
151 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
152 MAB = getTarget().createMCAsmBackend(getTargetTriple());
155 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
162 AsmStreamer.reset(S);
165 case CGFT_ObjectFile: {
166 // Create the code emitter for the target if it exists. If not, .o file
168 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
170 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
171 if (MCE == 0 || MAB == 0)
174 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
176 MCE, hasMCRelaxAll(),
177 hasMCNoExecStack()));
178 AsmStreamer.get()->InitSections();
182 // The Null output is intended for use for performance analysis and testing,
184 AsmStreamer.reset(createNullStreamer(*Context));
189 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
191 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
192 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
196 // If successful, createAsmPrinter took ownership of AsmStreamer.
201 PM.add(createGCInfoDeleter());
205 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
206 /// get machine code emitted. This uses a JITCodeEmitter object to handle
207 /// actually outputting the machine code and resolving things like the address
208 /// of functions. This method should returns true if machine code emission is
211 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
213 CodeGenOpt::Level OptLevel,
214 bool DisableVerify) {
215 // Add common CodeGen passes.
217 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
220 addCodeEmitter(PM, OptLevel, JCE);
221 PM.add(createGCInfoDeleter());
223 return false; // success!
226 /// addPassesToEmitMC - Add passes to the specified pass manager to get
227 /// machine code emitted with the MCJIT. This method returns true if machine
228 /// code is not supported. It fills the MCContext Ctx pointer which can be
229 /// used to build custom MCStreamer.
231 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
234 CodeGenOpt::Level OptLevel,
235 bool DisableVerify) {
236 // Add common CodeGen passes.
237 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
240 if (hasMCSaveTempLabels())
241 Ctx->setAllowTemporaryLabels(false);
243 // Create the code emitter for the target if it exists. If not, .o file
245 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
246 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
247 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
248 if (MCE == 0 || MAB == 0)
251 OwningPtr<MCStreamer> AsmStreamer;
252 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *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 return false; // success!
271 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
272 if (PrintMachineCode)
273 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
276 static void printAndVerify(PassManagerBase &PM,
277 const char *Banner) {
278 if (PrintMachineCode)
279 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
281 if (VerifyMachineCode)
282 PM.add(createMachineVerifierPass(Banner));
285 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
286 /// emitting to assembly files or machine code output.
288 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
289 CodeGenOpt::Level OptLevel,
291 MCContext *&OutContext) {
292 // Standard LLVM-Level Passes.
294 // Basic AliasAnalysis support.
295 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
296 // BasicAliasAnalysis wins if they disagree. This is intended to help
297 // support "obvious" type-punning idioms.
298 PM.add(createTypeBasedAliasAnalysisPass());
299 PM.add(createBasicAliasAnalysisPass());
301 // Before running any passes, run the verifier to determine if the input
302 // coming from the front-end and/or optimizer is valid.
304 PM.add(createVerifierPass());
306 // Run loop strength reduction before anything else.
307 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
308 PM.add(createLoopStrengthReducePass(getTargetLowering()));
310 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
313 PM.add(createGCLoweringPass());
315 // Make sure that no unreachable blocks are instruction selected.
316 PM.add(createUnreachableBlockEliminationPass());
318 // Turn exception handling constructs into something the code generators can
320 switch (getMCAsmInfo()->getExceptionHandlingType()) {
321 case ExceptionHandling::SjLj:
322 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
323 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
324 // catch info can get misplaced when a selector ends up more than one block
325 // removed from the parent invoke(s). This could happen when a landing
326 // pad is shared by multiple invokes and is also a target of a normal
327 // edge from elsewhere.
328 if (!DisableOldSjLjEH)
329 PM.add(createSjLjEHPass(getTargetLowering()));
331 case ExceptionHandling::DwarfCFI:
332 case ExceptionHandling::ARM:
333 case ExceptionHandling::Win64:
334 PM.add(createDwarfEHPass(this));
336 case ExceptionHandling::None:
337 PM.add(createLowerInvokePass(getTargetLowering()));
339 // The lower invoke pass may create unreachable code. Remove it.
340 PM.add(createUnreachableBlockEliminationPass());
344 if (OptLevel != CodeGenOpt::None && !DisableCGP)
345 PM.add(createCodeGenPreparePass(getTargetLowering()));
347 PM.add(createStackProtectorPass(getTargetLowering()));
349 addPreISel(PM, OptLevel);
352 PM.add(createPrintFunctionPass("\n\n"
353 "*** Final LLVM Code input to ISel ***\n",
356 // All passes which modify the LLVM IR are now complete; run the verifier
357 // to ensure that the IR is valid.
359 PM.add(createVerifierPass());
361 // Standard Lower-Level Passes.
363 // Install a MachineModuleInfo class, which is an immutable pass that holds
364 // all the per-module stuff we're generating, including MCContext.
365 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
367 &getTargetLowering()->getObjFileLowering());
369 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
371 // Set up a MachineFunction for the rest of CodeGen to work on.
372 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
374 // Enable FastISel with -fast, but allow that to be overridden.
375 if (EnableFastISelOption == cl::BOU_TRUE ||
376 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
377 EnableFastISel = true;
379 // Ask the target for an isel.
380 if (addInstSelector(PM, OptLevel))
383 // Print the instruction selected machine code...
384 printAndVerify(PM, "After Instruction Selection");
386 // Expand pseudo-instructions emitted by ISel.
387 PM.add(createExpandISelPseudosPass());
389 // Pre-ra tail duplication.
390 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
391 PM.add(createTailDuplicatePass(true));
392 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
395 // Optimize PHIs before DCE: removing dead PHI cycles may make more
396 // instructions dead.
397 if (OptLevel != CodeGenOpt::None)
398 PM.add(createOptimizePHIsPass());
400 // If the target requests it, assign local variables to stack slots relative
401 // to one another and simplify frame index references where possible.
402 PM.add(createLocalStackSlotAllocationPass());
404 if (OptLevel != CodeGenOpt::None) {
405 // With optimization, dead code should already be eliminated. However
406 // there is one known exception: lowered code for arguments that are only
407 // used by tail calls, where the tail calls reuse the incoming stack
408 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
409 if (!DisableMachineDCE)
410 PM.add(createDeadMachineInstructionElimPass());
411 printAndVerify(PM, "After codegen DCE pass");
413 if (!DisableMachineLICM)
414 PM.add(createMachineLICMPass());
415 if (!DisableMachineCSE)
416 PM.add(createMachineCSEPass());
417 if (!DisableMachineSink)
418 PM.add(createMachineSinkingPass());
419 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
421 PM.add(createPeepholeOptimizerPass());
422 printAndVerify(PM, "After codegen peephole optimization pass");
425 // Run pre-ra passes.
426 if (addPreRegAlloc(PM, OptLevel))
427 printAndVerify(PM, "After PreRegAlloc passes");
429 // Perform register allocation.
430 PM.add(createRegisterAllocator(OptLevel));
431 printAndVerify(PM, "After Register Allocation");
433 // Perform stack slot coloring and post-ra machine LICM.
434 if (OptLevel != CodeGenOpt::None) {
435 // FIXME: Re-enable coloring with register when it's capable of adding
438 PM.add(createStackSlotColoringPass(false));
440 // Run post-ra machine LICM to hoist reloads / remats.
441 if (!DisablePostRAMachineLICM)
442 PM.add(createMachineLICMPass(false));
444 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
447 // Run post-ra passes.
448 if (addPostRegAlloc(PM, OptLevel))
449 printAndVerify(PM, "After PostRegAlloc passes");
451 PM.add(createExpandPostRAPseudosPass());
452 printAndVerify(PM, "After ExpandPostRAPseudos");
454 // Insert prolog/epilog code. Eliminate abstract frame index references...
455 PM.add(createPrologEpilogCodeInserter());
456 printAndVerify(PM, "After PrologEpilogCodeInserter");
458 // Run pre-sched2 passes.
459 if (addPreSched2(PM, OptLevel))
460 printAndVerify(PM, "After PreSched2 passes");
462 // Second pass scheduler.
463 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
464 PM.add(createPostRAScheduler(OptLevel));
465 printAndVerify(PM, "After PostRAScheduler");
468 // Branch folding must be run after regalloc and prolog/epilog insertion.
469 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
470 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
471 printNoVerify(PM, "After BranchFolding");
475 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
476 PM.add(createTailDuplicatePass(false));
477 printNoVerify(PM, "After TailDuplicate");
480 PM.add(createGCMachineCodeAnalysisPass());
483 PM.add(createGCInfoPrinter(dbgs()));
485 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
486 PM.add(createCodePlacementOptPass());
487 printNoVerify(PM, "After CodePlacementOpt");
490 if (addPreEmitPass(PM, OptLevel))
491 printNoVerify(PM, "After PreEmit passes");