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 different directory between LLVM 2.9 and 3.0,
118 // and if the old one gets included then MCAsmInfo will be NULL and we'd crash
120 // Provide the user a useful error message about whats wrong.
121 assert(AsmInfo && "MCAsmInfo not initialized. Make sure you include the correct TargetSelect.h!");
124 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
125 formatted_raw_ostream &Out,
126 CodeGenFileType FileType,
127 CodeGenOpt::Level OptLevel,
128 bool DisableVerify) {
129 // Add common CodeGen passes.
130 MCContext *Context = 0;
131 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context))
133 assert(Context != 0 && "Failed to get MCContext");
135 if (hasMCSaveTempLabels())
136 Context->setAllowTemporaryLabels(false);
138 const MCAsmInfo &MAI = *getMCAsmInfo();
139 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
140 OwningPtr<MCStreamer> AsmStreamer;
143 default: return true;
144 case CGFT_AssemblyFile: {
145 MCInstPrinter *InstPrinter =
146 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
148 // Create a code emitter if asked to show the encoding.
149 MCCodeEmitter *MCE = 0;
150 MCAsmBackend *MAB = 0;
151 if (ShowMCEncoding) {
152 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
153 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
154 MAB = getTarget().createMCAsmBackend(getTargetTriple());
157 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
164 AsmStreamer.reset(S);
167 case CGFT_ObjectFile: {
168 // Create the code emitter for the target if it exists. If not, .o file
170 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
172 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
173 if (MCE == 0 || MAB == 0)
176 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
178 MCE, hasMCRelaxAll(),
179 hasMCNoExecStack()));
180 AsmStreamer.get()->InitSections();
184 // The Null output is intended for use for performance analysis and testing,
186 AsmStreamer.reset(createNullStreamer(*Context));
191 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs()));
193 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
194 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
198 // If successful, createAsmPrinter took ownership of AsmStreamer.
203 PM.add(createGCInfoDeleter());
207 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
208 /// get machine code emitted. This uses a JITCodeEmitter object to handle
209 /// actually outputting the machine code and resolving things like the address
210 /// of functions. This method should returns true if machine code emission is
213 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
215 CodeGenOpt::Level OptLevel,
216 bool DisableVerify) {
217 // Add common CodeGen passes.
219 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
222 addCodeEmitter(PM, OptLevel, JCE);
223 PM.add(createGCInfoDeleter());
225 return false; // success!
228 /// addPassesToEmitMC - Add passes to the specified pass manager to get
229 /// machine code emitted with the MCJIT. This method returns true if machine
230 /// code is not supported. It fills the MCContext Ctx pointer which can be
231 /// used to build custom MCStreamer.
233 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
236 CodeGenOpt::Level OptLevel,
237 bool DisableVerify) {
238 // Add common CodeGen passes.
239 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx))
242 if (hasMCSaveTempLabels())
243 Ctx->setAllowTemporaryLabels(false);
245 // Create the code emitter for the target if it exists. If not, .o file
247 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
248 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
249 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
250 if (MCE == 0 || MAB == 0)
253 OwningPtr<MCStreamer> AsmStreamer;
254 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
257 hasMCNoExecStack()));
258 AsmStreamer.get()->InitSections();
260 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
261 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
265 // If successful, createAsmPrinter took ownership of AsmStreamer.
270 return false; // success!
273 static void printNoVerify(PassManagerBase &PM, const char *Banner) {
274 if (PrintMachineCode)
275 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
278 static void printAndVerify(PassManagerBase &PM,
279 const char *Banner) {
280 if (PrintMachineCode)
281 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
283 if (VerifyMachineCode)
284 PM.add(createMachineVerifierPass(Banner));
287 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both
288 /// emitting to assembly files or machine code output.
290 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM,
291 CodeGenOpt::Level OptLevel,
293 MCContext *&OutContext) {
294 // Standard LLVM-Level Passes.
296 // Basic AliasAnalysis support.
297 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
298 // BasicAliasAnalysis wins if they disagree. This is intended to help
299 // support "obvious" type-punning idioms.
300 PM.add(createTypeBasedAliasAnalysisPass());
301 PM.add(createBasicAliasAnalysisPass());
303 // Before running any passes, run the verifier to determine if the input
304 // coming from the front-end and/or optimizer is valid.
306 PM.add(createVerifierPass());
308 // Run loop strength reduction before anything else.
309 if (OptLevel != CodeGenOpt::None && !DisableLSR) {
310 PM.add(createLoopStrengthReducePass(getTargetLowering()));
312 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
315 PM.add(createGCLoweringPass());
317 // Make sure that no unreachable blocks are instruction selected.
318 PM.add(createUnreachableBlockEliminationPass());
320 // Turn exception handling constructs into something the code generators can
322 switch (getMCAsmInfo()->getExceptionHandlingType()) {
323 case ExceptionHandling::SjLj:
324 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
325 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
326 // catch info can get misplaced when a selector ends up more than one block
327 // removed from the parent invoke(s). This could happen when a landing
328 // pad is shared by multiple invokes and is also a target of a normal
329 // edge from elsewhere.
330 PM.add(createSjLjEHPass(getTargetLowering()));
332 case ExceptionHandling::DwarfCFI:
333 case ExceptionHandling::ARM:
334 case ExceptionHandling::Win64:
335 PM.add(createDwarfEHPass(this));
337 case ExceptionHandling::None:
338 PM.add(createLowerInvokePass(getTargetLowering()));
340 // The lower invoke pass may create unreachable code. Remove it.
341 PM.add(createUnreachableBlockEliminationPass());
345 if (OptLevel != CodeGenOpt::None && !DisableCGP)
346 PM.add(createCodeGenPreparePass(getTargetLowering()));
348 PM.add(createStackProtectorPass(getTargetLowering()));
350 addPreISel(PM, OptLevel);
353 PM.add(createPrintFunctionPass("\n\n"
354 "*** Final LLVM Code input to ISel ***\n",
357 // All passes which modify the LLVM IR are now complete; run the verifier
358 // to ensure that the IR is valid.
360 PM.add(createVerifierPass());
362 // Standard Lower-Level Passes.
364 // Install a MachineModuleInfo class, which is an immutable pass that holds
365 // all the per-module stuff we're generating, including MCContext.
366 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(),
368 &getTargetLowering()->getObjFileLowering());
370 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
372 // Set up a MachineFunction for the rest of CodeGen to work on.
373 PM.add(new MachineFunctionAnalysis(*this, OptLevel));
375 // Enable FastISel with -fast, but allow that to be overridden.
376 if (EnableFastISelOption == cl::BOU_TRUE ||
377 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE))
378 EnableFastISel = true;
380 // Ask the target for an isel.
381 if (addInstSelector(PM, OptLevel))
384 // Print the instruction selected machine code...
385 printAndVerify(PM, "After Instruction Selection");
387 // Expand pseudo-instructions emitted by ISel.
388 PM.add(createExpandISelPseudosPass());
390 // Pre-ra tail duplication.
391 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) {
392 PM.add(createTailDuplicatePass(true));
393 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate");
396 // Optimize PHIs before DCE: removing dead PHI cycles may make more
397 // instructions dead.
398 if (OptLevel != CodeGenOpt::None)
399 PM.add(createOptimizePHIsPass());
401 // If the target requests it, assign local variables to stack slots relative
402 // to one another and simplify frame index references where possible.
403 PM.add(createLocalStackSlotAllocationPass());
405 if (OptLevel != CodeGenOpt::None) {
406 // With optimization, dead code should already be eliminated. However
407 // there is one known exception: lowered code for arguments that are only
408 // used by tail calls, where the tail calls reuse the incoming stack
409 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
410 if (!DisableMachineDCE)
411 PM.add(createDeadMachineInstructionElimPass());
412 printAndVerify(PM, "After codegen DCE pass");
414 if (!DisableMachineLICM)
415 PM.add(createMachineLICMPass());
416 if (!DisableMachineCSE)
417 PM.add(createMachineCSEPass());
418 if (!DisableMachineSink)
419 PM.add(createMachineSinkingPass());
420 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes");
422 PM.add(createPeepholeOptimizerPass());
423 printAndVerify(PM, "After codegen peephole optimization pass");
426 // Run pre-ra passes.
427 if (addPreRegAlloc(PM, OptLevel))
428 printAndVerify(PM, "After PreRegAlloc passes");
430 // Perform register allocation.
431 PM.add(createRegisterAllocator(OptLevel));
432 printAndVerify(PM, "After Register Allocation");
434 // Perform stack slot coloring and post-ra machine LICM.
435 if (OptLevel != CodeGenOpt::None) {
436 // FIXME: Re-enable coloring with register when it's capable of adding
439 PM.add(createStackSlotColoringPass(false));
441 // Run post-ra machine LICM to hoist reloads / remats.
442 if (!DisablePostRAMachineLICM)
443 PM.add(createMachineLICMPass(false));
445 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM");
448 // Run post-ra passes.
449 if (addPostRegAlloc(PM, OptLevel))
450 printAndVerify(PM, "After PostRegAlloc passes");
452 PM.add(createExpandPostRAPseudosPass());
453 printAndVerify(PM, "After ExpandPostRAPseudos");
455 // Insert prolog/epilog code. Eliminate abstract frame index references...
456 PM.add(createPrologEpilogCodeInserter());
457 printAndVerify(PM, "After PrologEpilogCodeInserter");
459 // Run pre-sched2 passes.
460 if (addPreSched2(PM, OptLevel))
461 printAndVerify(PM, "After PreSched2 passes");
463 // Second pass scheduler.
464 if (OptLevel != CodeGenOpt::None && !DisablePostRA) {
465 PM.add(createPostRAScheduler(OptLevel));
466 printAndVerify(PM, "After PostRAScheduler");
469 // Branch folding must be run after regalloc and prolog/epilog insertion.
470 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) {
471 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
472 printNoVerify(PM, "After BranchFolding");
476 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) {
477 PM.add(createTailDuplicatePass(false));
478 printNoVerify(PM, "After TailDuplicate");
481 PM.add(createGCMachineCodeAnalysisPass());
484 PM.add(createGCInfoPrinter(dbgs()));
486 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) {
487 PM.add(createCodePlacementOptPass());
488 printNoVerify(PM, "After CodePlacementOpt");
491 if (addPreEmitPass(PM, OptLevel))
492 printNoVerify(PM, "After PreEmit passes");