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> 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> DisableMachineDCE("disable-machine-dce", cl::Hidden,
61 cl::desc("Disable Machine Dead Code Elimination"));
62 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden,
63 cl::desc("Disable Machine LICM"));
64 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden,
65 cl::desc("Disable Machine Common Subexpression Elimination"));
66 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm",
68 cl::desc("Disable Machine LICM"));
69 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden,
70 cl::desc("Disable Machine Sinking"));
71 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden,
72 cl::desc("Disable Loop Strength Reduction Pass"));
73 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden,
74 cl::desc("Disable Codegen Prepare"));
75 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
76 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
77 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
78 cl::desc("Print LLVM IR input to isel pass"));
79 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
80 cl::desc("Dump garbage collector data"));
81 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
82 cl::desc("Show encoding in .s output"));
83 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
84 cl::desc("Show instruction structure in .s output"));
85 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden,
86 cl::desc("Enable MC API logging"));
87 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
88 cl::desc("Verify generated machine code"),
89 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
91 static cl::opt<cl::boolOrDefault>
92 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
93 cl::init(cl::BOU_UNSET));
95 static bool getVerboseAsm() {
98 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
99 case cl::BOU_TRUE: return true;
100 case cl::BOU_FALSE: return false;
104 // Enable or disable FastISel. Both options are needed, because
105 // FastISel is enabled by default with -fast, and we wish to be
106 // able to enable or disable fast-isel independently from -O0.
107 static cl::opt<cl::boolOrDefault>
108 EnableFastISelOption("fast-isel", cl::Hidden,
109 cl::desc("Enable the \"fast\" instruction selector"));
111 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
112 StringRef CPU, StringRef FS,
113 Reloc::Model RM, CodeModel::Model CM)
114 : TargetMachine(T, Triple, CPU, FS) {
115 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM);
116 AsmInfo = T.createMCAsmInfo(Triple);
117 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
118 // and if the old one gets included then MCAsmInfo will be NULL and
119 // we'll crash later.
120 // Provide the user with a useful error message about what's wrong.
121 assert(AsmInfo && "MCAsmInfo not initialized."
122 "Make sure you include the correct TargetSelect.h!");
125 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
126 formatted_raw_ostream &Out,
127 CodeGenFileType FileType,
128 CodeGenOpt::Level OptLevel,
129 bool DisableVerify) {
130 // Add common CodeGen passes.
131 MCContext *Context = 0;
132 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
134 assert(Context != 0 && "Failed to get MCContext");
136 if (hasMCSaveTempLabels())
137 Context->setAllowTemporaryLabels(false);
139 const MCAsmInfo &MAI = *getMCAsmInfo();
140 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
141 OwningPtr<MCStreamer> AsmStreamer;
144 default: return true;
145 case CGFT_AssemblyFile: {
146 MCInstPrinter *InstPrinter =
147 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
149 // Create a code emitter if asked to show the encoding.
150 MCCodeEmitter *MCE = 0;
151 MCAsmBackend *MAB = 0;
152 if (ShowMCEncoding) {
153 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
154 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
155 MAB = getTarget().createMCAsmBackend(getTargetTriple());
158 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
165 AsmStreamer.reset(S);
168 case CGFT_ObjectFile: {
169 // Create the code emitter for the target if it exists. If not, .o file
171 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
173 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
174 if (MCE == 0 || MAB == 0)
177 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
179 MCE, hasMCRelaxAll(),
180 hasMCNoExecStack()));
181 AsmStreamer.get()->InitSections();
185 // The Null output is intended for use for performance analysis and testing,
187 AsmStreamer.reset(createNullStreamer(*Context));
192 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
194 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
195 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
199 // If successful, createAsmPrinter took ownership of AsmStreamer.
204 PM.add(createGCInfoDeleter());
208 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
209 /// get machine code emitted. This uses a JITCodeEmitter object to handle
210 /// actually outputting the machine code and resolving things like the address
211 /// of functions. This method should returns true if machine code emission is
214 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
216 CodeGenOpt::Level OptLevel,
217 bool DisableVerify) {
218 // Add common CodeGen passes.
220 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
223 addCodeEmitter(PM, OptLevel, JCE);
224 PM.add(createGCInfoDeleter());
226 return false; // success!
229 /// addPassesToEmitMC - Add passes to the specified pass manager to get
230 /// machine code emitted with the MCJIT. This method returns true if machine
231 /// code is not supported. It fills the MCContext Ctx pointer which can be
232 /// used to build custom MCStreamer.
234 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
237 CodeGenOpt::Level OptLevel,
238 bool DisableVerify) {
239 // Add common CodeGen passes.
240 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
243 if (hasMCSaveTempLabels())
244 Ctx->setAllowTemporaryLabels(false);
246 // Create the code emitter for the target if it exists. If not, .o file
248 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
249 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
250 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
251 if (MCE == 0 || MAB == 0)
254 OwningPtr<MCStreamer> AsmStreamer;
255 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
258 hasMCNoExecStack()));
259 AsmStreamer.get()->InitSections();
261 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
262 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
266 // If successful, createAsmPrinter took ownership of AsmStreamer.
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 // Run loop strength reduction before anything else.
310 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
311 PM.add(createLoopStrengthReducePass(getTargetLowering()));
313 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
316 PM.add(createGCLoweringPass());
318 // Make sure that no unreachable blocks are instruction selected.
319 PM.add(createUnreachableBlockEliminationPass());
321 // Turn exception handling constructs into something the code generators can
323 switch (getMCAsmInfo()->getExceptionHandlingType()) {
324 case ExceptionHandling::SjLj:
325 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
326 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
327 // catch info can get misplaced when a selector ends up more than one block
328 // removed from the parent invoke(s). This could happen when a landing
329 // pad is shared by multiple invokes and is also a target of a normal
330 // edge from elsewhere.
331 PM.add(createSjLjEHPass(getTargetLowering()));
333 case ExceptionHandling::DwarfCFI:
334 case ExceptionHandling::ARM:
335 case ExceptionHandling::Win64:
336 PM.add(createDwarfEHPass(this));
338 case ExceptionHandling::None:
339 PM.add(createLowerInvokePass(getTargetLowering()));
341 // The lower invoke pass may create unreachable code. Remove it.
342 PM.add(createUnreachableBlockEliminationPass());
346 if (OptLevel != CodeGenOpt::None && !DisableCGP)
347 PM.add(createCodeGenPreparePass(getTargetLowering()));
349 PM.add(createStackProtectorPass(getTargetLowering()));
351 addPreISel(PM, OptLevel);
354 PM.add(createPrintFunctionPass("\n\n"
355 "*** Final LLVM Code input to ISel ***\n",
358 // All passes which modify the LLVM IR are now complete; run the verifier
359 // to ensure that the IR is valid.
361 PM.add(createVerifierPass());
363 // Standard Lower-Level Passes.
365 // Install a MachineModuleInfo class, which is an immutable pass that holds
366 // all the per-module stuff we're generating, including MCContext.
367 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
369 &getTargetLowering()->getObjFileLowering());
371 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
373 // Set up a MachineFunction for the rest of CodeGen to work on.
374 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
376 // Enable FastISel with -fast, but allow that to be overridden.
377 if (EnableFastISelOption == cl::BOU_TRUE ||
378 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
379 EnableFastISel = true;
381 // Ask the target for an isel.
382 if (addInstSelector(PM, OptLevel))
385 // Print the instruction selected machine code...
386 printAndVerify(PM, "After Instruction Selection");
388 // Expand pseudo-instructions emitted by ISel.
389 PM.add(createExpandISelPseudosPass());
391 // Pre-ra tail duplication.
392 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
393 PM.add(createTailDuplicatePass(true));
394 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
397 // Optimize PHIs before DCE: removing dead PHI cycles may make more
398 // instructions dead.
399 if (OptLevel != CodeGenOpt::None)
400 PM.add(createOptimizePHIsPass());
402 // If the target requests it, assign local variables to stack slots relative
403 // to one another and simplify frame index references where possible.
404 PM.add(createLocalStackSlotAllocationPass());
406 if (OptLevel != CodeGenOpt::None) {
407 // With optimization, dead code should already be eliminated. However
408 // there is one known exception: lowered code for arguments that are only
409 // used by tail calls, where the tail calls reuse the incoming stack
410 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
411 if (!DisableMachineDCE)
412 PM.add(createDeadMachineInstructionElimPass());
413 printAndVerify(PM, "After codegen DCE pass");
415 if (!DisableMachineLICM)
416 PM.add(createMachineLICMPass());
417 if (!DisableMachineCSE)
418 PM.add(createMachineCSEPass());
419 if (!DisableMachineSink)
420 PM.add(createMachineSinkingPass());
421 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
423 PM.add(createPeepholeOptimizerPass());
424 printAndVerify(PM, "After codegen peephole optimization pass");
427 // Run pre-ra passes.
428 if (addPreRegAlloc(PM, OptLevel))
429 printAndVerify(PM, "After PreRegAlloc passes");
431 // Perform register allocation.
432 PM.add(createRegisterAllocator(OptLevel));
433 printAndVerify(PM, "After Register Allocation");
435 // Perform stack slot coloring and post-ra machine LICM.
436 if (OptLevel != CodeGenOpt::None) {
437 // FIXME: Re-enable coloring with register when it's capable of adding
440 PM.add(createStackSlotColoringPass(false));
442 // Run post-ra machine LICM to hoist reloads / remats.
443 if (!DisablePostRAMachineLICM)
444 PM.add(createMachineLICMPass(false));
446 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
449 // Run post-ra passes.
450 if (addPostRegAlloc(PM, OptLevel))
451 printAndVerify(PM, "After PostRegAlloc passes");
453 PM.add(createExpandPostRAPseudosPass());
454 printAndVerify(PM, "After ExpandPostRAPseudos");
456 // Insert prolog/epilog code. Eliminate abstract frame index references...
457 PM.add(createPrologEpilogCodeInserter());
458 printAndVerify(PM, "After PrologEpilogCodeInserter");
460 // Run pre-sched2 passes.
461 if (addPreSched2(PM, OptLevel))
462 printAndVerify(PM, "After PreSched2 passes");
464 // Second pass scheduler.
465 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
466 PM.add(createPostRAScheduler(OptLevel));
467 printAndVerify(PM, "After PostRAScheduler");
470 // Branch folding must be run after regalloc and prolog/epilog insertion.
471 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
472 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
473 printNoVerify(PM, "After BranchFolding");
477 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
478 PM.add(createTailDuplicatePass(false));
479 printNoVerify(PM, "After TailDuplicate");
482 PM.add(createGCMachineCodeAnalysisPass());
485 PM.add(createGCInfoPrinter(dbgs()));
487 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
488 PM.add(createCodePlacementOptPass());
489 printNoVerify(PM, "After CodePlacementOpt");
492 if (addPreEmitPass(PM, OptLevel))
493 printNoVerify(PM, "After PreEmit passes");