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"
44 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden,
45 cl::desc("Disable Post Regalloc"));
46 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden,
47 cl::desc("Disable branch folding"));
48 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden,
49 cl::desc("Disable tail duplication"));
50 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden,
51 cl::desc("Disable pre-register allocation tail duplication"));
52 static cl::opt<bool> EnableBlockPlacement("enable-block-placement",
53 cl::Hidden, cl::desc("Enable probability-driven block placement"));
54 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats",
55 cl::Hidden, cl::desc("Collect probability-driven block placement stats"));
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> VerifyMachineCode("verify-machineinstrs", cl::Hidden,
86 cl::desc("Verify generated machine code"),
87 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL));
89 static cl::opt<cl::boolOrDefault>
90 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."),
91 cl::init(cl::BOU_UNSET));
93 static bool getVerboseAsm() {
96 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
97 case cl::BOU_TRUE: return true;
98 case cl::BOU_FALSE: return false;
102 // Enable or disable FastISel. Both options are needed, because
103 // FastISel is enabled by default with -fast, and we wish to be
104 // able to enable or disable fast-isel independently from -O0.
105 static cl::opt<cl::boolOrDefault>
106 EnableFastISelOption("fast-isel", cl::Hidden,
107 cl::desc("Enable the \"fast\" instruction selector"));
109 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple,
110 StringRef CPU, StringRef FS,
111 TargetOptions Options,
112 Reloc::Model RM, CodeModel::Model CM,
113 CodeGenOpt::Level OL)
114 : TargetMachine(T, Triple, CPU, FS, Options) {
115 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
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"
123 "and that InitializeAllTargetMCs() is being invoked!");
126 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
127 formatted_raw_ostream &Out,
128 CodeGenFileType FileType,
129 bool DisableVerify) {
130 // Add common CodeGen passes.
131 MCContext *Context = 0;
132 if (addCommonCodeGenPasses(PM, 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,
162 hasMCUseDwarfDirectory(),
166 AsmStreamer.reset(S);
169 case CGFT_ObjectFile: {
170 // Create the code emitter for the target if it exists. If not, .o file
172 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
174 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
175 if (MCE == 0 || MAB == 0)
178 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
180 MCE, hasMCRelaxAll(),
181 hasMCNoExecStack()));
182 AsmStreamer.get()->InitSections();
186 // The Null output is intended for use for performance analysis and testing,
188 AsmStreamer.reset(createNullStreamer(*Context));
192 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
193 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
197 // If successful, createAsmPrinter took ownership of AsmStreamer.
202 PM.add(createGCInfoDeleter());
206 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
207 /// get machine code emitted. This uses a JITCodeEmitter object to handle
208 /// actually outputting the machine code and resolving things like the address
209 /// of functions. This method should returns true if machine code emission is
212 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
214 bool DisableVerify) {
215 // Add common CodeGen passes.
217 if (addCommonCodeGenPasses(PM, DisableVerify, Ctx))
220 addCodeEmitter(PM, 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 bool DisableVerify) {
235 // Add common CodeGen passes.
236 if (addCommonCodeGenPasses(PM, DisableVerify, Ctx))
239 if (hasMCSaveTempLabels())
240 Ctx->setAllowTemporaryLabels(false);
242 // Create the code emitter for the target if it exists. If not, .o file
244 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
245 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
246 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
247 if (MCE == 0 || MAB == 0)
250 OwningPtr<MCStreamer> AsmStreamer;
251 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
254 hasMCNoExecStack()));
255 AsmStreamer.get()->InitSections();
257 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
258 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
262 // If successful, createAsmPrinter took ownership of AsmStreamer.
267 return false; // success!
270 void LLVMTargetMachine::printNoVerify(PassManagerBase &PM,
271 const char *Banner) const {
272 if (Options.PrintMachineCode)
273 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
276 void LLVMTargetMachine::printAndVerify(PassManagerBase &PM,
277 const char *Banner) const {
278 if (Options.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,
290 MCContext *&OutContext) {
291 // Standard LLVM-Level Passes.
293 // Basic AliasAnalysis support.
294 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
295 // BasicAliasAnalysis wins if they disagree. This is intended to help
296 // support "obvious" type-punning idioms.
297 PM.add(createTypeBasedAliasAnalysisPass());
298 PM.add(createBasicAliasAnalysisPass());
300 // Before running any passes, run the verifier to determine if the input
301 // coming from the front-end and/or optimizer is valid.
303 PM.add(createVerifierPass());
305 // Run loop strength reduction before anything else.
306 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
307 PM.add(createLoopStrengthReducePass(getTargetLowering()));
309 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
312 PM.add(createGCLoweringPass());
314 // Make sure that no unreachable blocks are instruction selected.
315 PM.add(createUnreachableBlockEliminationPass());
317 // Turn exception handling constructs into something the code generators can
319 switch (getMCAsmInfo()->getExceptionHandlingType()) {
320 case ExceptionHandling::SjLj:
321 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
322 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
323 // catch info can get misplaced when a selector ends up more than one block
324 // removed from the parent invoke(s). This could happen when a landing
325 // pad is shared by multiple invokes and is also a target of a normal
326 // edge from elsewhere.
327 PM.add(createSjLjEHPass(getTargetLowering()));
329 case ExceptionHandling::DwarfCFI:
330 case ExceptionHandling::ARM:
331 case ExceptionHandling::Win64:
332 PM.add(createDwarfEHPass(this));
334 case ExceptionHandling::None:
335 PM.add(createLowerInvokePass(getTargetLowering()));
337 // The lower invoke pass may create unreachable code. Remove it.
338 PM.add(createUnreachableBlockEliminationPass());
342 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
343 PM.add(createCodeGenPreparePass(getTargetLowering()));
345 PM.add(createStackProtectorPass(getTargetLowering()));
350 PM.add(createPrintFunctionPass("\n\n"
351 "*** Final LLVM Code input to ISel ***\n",
354 // All passes which modify the LLVM IR are now complete; run the verifier
355 // to ensure that the IR is valid.
357 PM.add(createVerifierPass());
359 // Standard Lower-Level Passes.
361 // Install a MachineModuleInfo class, which is an immutable pass that holds
362 // all the per-module stuff we're generating, including MCContext.
363 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
365 &getTargetLowering()->getObjFileLowering());
367 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
369 // Set up a MachineFunction for the rest of CodeGen to work on.
370 PM.add(new MachineFunctionAnalysis(*this));
372 // Enable FastISel with -fast, but allow that to be overridden.
373 if (EnableFastISelOption == cl::BOU_TRUE ||
374 (getOptLevel() == CodeGenOpt::None &&
375 EnableFastISelOption != cl::BOU_FALSE))
376 Options.EnableFastISel = true;
378 // Ask the target for an isel.
379 if (addInstSelector(PM))
382 // Print the instruction selected machine code...
383 printAndVerify(PM, "After Instruction Selection");
385 // Expand pseudo-instructions emitted by ISel.
386 PM.add(createExpandISelPseudosPass());
388 // Pre-ra tail duplication.
389 if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
390 PM.add(createTailDuplicatePass(true));
391 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
394 // Optimize PHIs before DCE: removing dead PHI cycles may make more
395 // instructions dead.
396 if (getOptLevel() != 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 (getOptLevel() != 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 if (!DisableMachineDCE)
409 PM.add(createDeadMachineInstructionElimPass());
410 printAndVerify(PM, "After codegen DCE pass");
412 if (!DisableMachineLICM)
413 PM.add(createMachineLICMPass());
414 if (!DisableMachineCSE)
415 PM.add(createMachineCSEPass());
416 if (!DisableMachineSink)
417 PM.add(createMachineSinkingPass());
418 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
420 PM.add(createPeepholeOptimizerPass());
421 printAndVerify(PM, "After codegen peephole optimization pass");
424 // Run pre-ra passes.
425 if (addPreRegAlloc(PM))
426 printAndVerify(PM, "After PreRegAlloc passes");
428 // Perform register allocation.
429 PM.add(createRegisterAllocator(getOptLevel()));
430 printAndVerify(PM, "After Register Allocation");
432 // Perform stack slot coloring and post-ra machine LICM.
433 if (getOptLevel() != CodeGenOpt::None) {
434 // FIXME: Re-enable coloring with register when it's capable of adding
437 PM.add(createStackSlotColoringPass(false));
439 // Run post-ra machine LICM to hoist reloads / remats.
440 if (!DisablePostRAMachineLICM)
441 PM.add(createMachineLICMPass(false));
443 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
446 // Run post-ra passes.
447 if (addPostRegAlloc(PM))
448 printAndVerify(PM, "After PostRegAlloc passes");
450 // Insert prolog/epilog code. Eliminate abstract frame index references...
451 PM.add(createPrologEpilogCodeInserter());
452 printAndVerify(PM, "After PrologEpilogCodeInserter");
454 // Branch folding must be run after regalloc and prolog/epilog insertion.
455 if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
456 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
457 printNoVerify(PM, "After BranchFolding");
461 if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
462 PM.add(createTailDuplicatePass(false));
463 printNoVerify(PM, "After TailDuplicate");
467 if (getOptLevel() != CodeGenOpt::None) {
468 PM.add(createMachineCopyPropagationPass());
469 printNoVerify(PM, "After copy propagation pass");
472 // Expand pseudo instructions before second scheduling pass.
473 PM.add(createExpandPostRAPseudosPass());
474 printNoVerify(PM, "After ExpandPostRAPseudos");
476 // Run pre-sched2 passes.
477 if (addPreSched2(PM))
478 printNoVerify(PM, "After PreSched2 passes");
480 // Second pass scheduler.
481 if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
482 PM.add(createPostRAScheduler(getOptLevel()));
483 printNoVerify(PM, "After PostRAScheduler");
486 PM.add(createGCMachineCodeAnalysisPass());
489 PM.add(createGCInfoPrinter(dbgs()));
491 if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
492 if (EnableBlockPlacement) {
493 // MachineBlockPlacement is an experimental pass which is disabled by
494 // default currently. Eventually it should subsume CodePlacementOpt, so
495 // when enabled, the other is disabled.
496 PM.add(createMachineBlockPlacementPass());
497 printNoVerify(PM, "After MachineBlockPlacement");
499 PM.add(createCodePlacementOptPass());
500 printNoVerify(PM, "After CodePlacementOpt");
503 // Run a separate pass to collect block placement statistics.
504 if (EnableBlockPlacementStats) {
505 PM.add(createMachineBlockPlacementStatsPass());
506 printNoVerify(PM, "After MachineBlockPlacementStats");
510 if (addPreEmitPass(PM))
511 printNoVerify(PM, "After PreEmit passes");