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> DisableCopyProp("disable-copyprop", cl::Hidden,
76 cl::desc("Disable Copy Propagation pass"));
77 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden,
78 cl::desc("Print LLVM IR produced by the loop-reduce pass"));
79 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden,
80 cl::desc("Print LLVM IR input to isel pass"));
81 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden,
82 cl::desc("Dump garbage collector data"));
83 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden,
84 cl::desc("Show encoding in .s output"));
85 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden,
86 cl::desc("Show instruction structure in .s output"));
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() {
97 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault();
98 case cl::BOU_TRUE: return true;
99 case cl::BOU_FALSE: return false;
101 llvm_unreachable("Invalid verbose asm state");
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 TargetOptions Options,
114 Reloc::Model RM, CodeModel::Model CM,
115 CodeGenOpt::Level OL)
116 : TargetMachine(T, Triple, CPU, FS, Options) {
117 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM, OL);
118 AsmInfo = T.createMCAsmInfo(Triple);
119 // TargetSelect.h moved to a different directory between LLVM 2.9 and 3.0,
120 // and if the old one gets included then MCAsmInfo will be NULL and
121 // we'll crash later.
122 // Provide the user with a useful error message about what's wrong.
123 assert(AsmInfo && "MCAsmInfo not initialized."
124 "Make sure you include the correct TargetSelect.h"
125 "and that InitializeAllTargetMCs() is being invoked!");
128 TargetPassConfig::TargetPassConfig(TargetMachine *tm, PassManagerBase &pm,
129 bool DisableVerifyFlag)
130 : TM(tm), PM(pm), DisableVerify(DisableVerifyFlag) {
131 // Register all target independent codegen passes to activate their PassIDs.
132 initializeCodeGen(*PassRegistry::getPassRegistry());
135 /// createPassConfig - Create a pass configuration object to be used by
136 /// addPassToEmitX methods for generating a pipeline of CodeGen passes.
137 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM,
138 bool DisableVerify) {
139 return new TargetPassConfig(this, PM, DisableVerify);
142 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM,
143 formatted_raw_ostream &Out,
144 CodeGenFileType FileType,
145 bool DisableVerify) {
146 // Add common CodeGen passes.
147 MCContext *Context = 0;
148 OwningPtr<TargetPassConfig> PassConfig(createPassConfig(PM, DisableVerify));
149 if (PassConfig->addCodeGenPasses(Context))
151 assert(Context != 0 && "Failed to get MCContext");
153 if (hasMCSaveTempLabels())
154 Context->setAllowTemporaryLabels(false);
156 const MCAsmInfo &MAI = *getMCAsmInfo();
157 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
158 OwningPtr<MCStreamer> AsmStreamer;
161 case CGFT_AssemblyFile: {
162 MCInstPrinter *InstPrinter =
163 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI);
165 // Create a code emitter if asked to show the encoding.
166 MCCodeEmitter *MCE = 0;
167 MCAsmBackend *MAB = 0;
168 if (ShowMCEncoding) {
169 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
170 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context);
171 MAB = getTarget().createMCAsmBackend(getTargetTriple());
174 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out,
178 hasMCUseDwarfDirectory(),
182 AsmStreamer.reset(S);
185 case CGFT_ObjectFile: {
186 // Create the code emitter for the target if it exists. If not, .o file
188 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI,
190 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
191 if (MCE == 0 || MAB == 0)
194 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(),
196 MCE, hasMCRelaxAll(),
197 hasMCNoExecStack()));
198 AsmStreamer.get()->InitSections();
202 // The Null output is intended for use for performance analysis and testing,
204 AsmStreamer.reset(createNullStreamer(*Context));
208 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
209 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
213 // If successful, createAsmPrinter took ownership of AsmStreamer.
218 PM.add(createGCInfoDeleter());
222 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to
223 /// get machine code emitted. This uses a JITCodeEmitter object to handle
224 /// actually outputting the machine code and resolving things like the address
225 /// of functions. This method should returns true if machine code emission is
228 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM,
230 bool DisableVerify) {
231 // Add common CodeGen passes.
233 OwningPtr<TargetPassConfig> PassConfig(createPassConfig(PM, DisableVerify));
234 if (PassConfig->addCodeGenPasses(Ctx))
237 addCodeEmitter(PM, JCE);
238 PM.add(createGCInfoDeleter());
240 return false; // success!
243 /// addPassesToEmitMC - Add passes to the specified pass manager to get
244 /// machine code emitted with the MCJIT. This method returns true if machine
245 /// code is not supported. It fills the MCContext Ctx pointer which can be
246 /// used to build custom MCStreamer.
248 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM,
251 bool DisableVerify) {
252 // Add common CodeGen passes.
253 OwningPtr<TargetPassConfig> PassConfig(createPassConfig(PM, DisableVerify));
254 if (PassConfig->addCodeGenPasses(Ctx))
257 if (hasMCSaveTempLabels())
258 Ctx->setAllowTemporaryLabels(false);
260 // Create the code emitter for the target if it exists. If not, .o file
262 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>();
263 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx);
264 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple());
265 if (MCE == 0 || MAB == 0)
268 OwningPtr<MCStreamer> AsmStreamer;
269 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx,
272 hasMCNoExecStack()));
273 AsmStreamer.get()->InitSections();
275 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful.
276 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer);
280 // If successful, createAsmPrinter took ownership of AsmStreamer.
285 return false; // success!
288 void TargetPassConfig::printNoVerify(const char *Banner) const {
289 if (TM->shouldPrintMachineCode())
290 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
293 void TargetPassConfig::printAndVerify(const char *Banner) const {
294 if (TM->shouldPrintMachineCode())
295 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner));
297 if (VerifyMachineCode)
298 PM.add(createMachineVerifierPass(Banner));
301 /// addCodeGenPasses - Add standard LLVM codegen passes used for both
302 /// emitting to assembly files or machine code output.
304 bool TargetPassConfig::addCodeGenPasses(MCContext *&OutContext) {
305 // Standard LLVM-Level Passes.
307 // Basic AliasAnalysis support.
308 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that
309 // BasicAliasAnalysis wins if they disagree. This is intended to help
310 // support "obvious" type-punning idioms.
311 PM.add(createTypeBasedAliasAnalysisPass());
312 PM.add(createBasicAliasAnalysisPass());
314 // Before running any passes, run the verifier to determine if the input
315 // coming from the front-end and/or optimizer is valid.
317 PM.add(createVerifierPass());
319 // Run loop strength reduction before anything else.
320 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) {
321 PM.add(createLoopStrengthReducePass(getTargetLowering()));
323 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs()));
326 PM.add(createGCLoweringPass());
328 // Make sure that no unreachable blocks are instruction selected.
329 PM.add(createUnreachableBlockEliminationPass());
331 // Turn exception handling constructs into something the code generators can
333 switch (TM->getMCAsmInfo()->getExceptionHandlingType()) {
334 case ExceptionHandling::SjLj:
335 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both
336 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise,
337 // catch info can get misplaced when a selector ends up more than one block
338 // removed from the parent invoke(s). This could happen when a landing
339 // pad is shared by multiple invokes and is also a target of a normal
340 // edge from elsewhere.
341 PM.add(createSjLjEHPass(getTargetLowering()));
343 case ExceptionHandling::DwarfCFI:
344 case ExceptionHandling::ARM:
345 case ExceptionHandling::Win64:
346 PM.add(createDwarfEHPass(TM));
348 case ExceptionHandling::None:
349 PM.add(createLowerInvokePass(getTargetLowering()));
351 // The lower invoke pass may create unreachable code. Remove it.
352 PM.add(createUnreachableBlockEliminationPass());
356 if (getOptLevel() != CodeGenOpt::None && !DisableCGP)
357 PM.add(createCodeGenPreparePass(getTargetLowering()));
359 PM.add(createStackProtectorPass(getTargetLowering()));
364 PM.add(createPrintFunctionPass("\n\n"
365 "*** Final LLVM Code input to ISel ***\n",
368 // All passes which modify the LLVM IR are now complete; run the verifier
369 // to ensure that the IR is valid.
371 PM.add(createVerifierPass());
373 // Standard Lower-Level Passes.
375 // Install a MachineModuleInfo class, which is an immutable pass that holds
376 // all the per-module stuff we're generating, including MCContext.
377 MachineModuleInfo *MMI =
378 new MachineModuleInfo(*TM->getMCAsmInfo(), *TM->getRegisterInfo(),
379 &getTargetLowering()->getObjFileLowering());
381 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref.
383 // Set up a MachineFunction for the rest of CodeGen to work on.
384 PM.add(new MachineFunctionAnalysis(*TM));
386 // Enable FastISel with -fast, but allow that to be overridden.
387 if (EnableFastISelOption == cl::BOU_TRUE ||
388 (getOptLevel() == CodeGenOpt::None &&
389 EnableFastISelOption != cl::BOU_FALSE))
390 TM->setFastISel(true);
392 // Ask the target for an isel.
393 if (addInstSelector())
396 // Print the instruction selected machine code...
397 printAndVerify("After Instruction Selection");
399 // Expand pseudo-instructions emitted by ISel.
400 PM.add(createExpandISelPseudosPass());
402 // Pre-ra tail duplication.
403 if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) {
404 PM.add(createTailDuplicatePass(true));
405 printAndVerify("After Pre-RegAlloc TailDuplicate");
408 // Optimize PHIs before DCE: removing dead PHI cycles may make more
409 // instructions dead.
410 if (getOptLevel() != CodeGenOpt::None)
411 PM.add(createOptimizePHIsPass());
413 // If the target requests it, assign local variables to stack slots relative
414 // to one another and simplify frame index references where possible.
415 PM.add(createLocalStackSlotAllocationPass());
417 if (getOptLevel() != CodeGenOpt::None) {
418 // With optimization, dead code should already be eliminated. However
419 // there is one known exception: lowered code for arguments that are only
420 // used by tail calls, where the tail calls reuse the incoming stack
421 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll).
422 if (!DisableMachineDCE)
423 PM.add(createDeadMachineInstructionElimPass());
424 printAndVerify("After codegen DCE pass");
426 if (!DisableMachineLICM)
427 PM.add(createMachineLICMPass());
428 if (!DisableMachineCSE)
429 PM.add(createMachineCSEPass());
430 if (!DisableMachineSink)
431 PM.add(createMachineSinkingPass());
432 printAndVerify("After Machine LICM, CSE and Sinking passes");
434 PM.add(createPeepholeOptimizerPass());
435 printAndVerify("After codegen peephole optimization pass");
438 // Run pre-ra passes.
439 if (addPreRegAlloc())
440 printAndVerify("After PreRegAlloc passes");
442 // Perform register allocation.
443 PM.add(createRegisterAllocator(getOptLevel()));
444 printAndVerify("After Register Allocation");
446 // Perform stack slot coloring and post-ra machine LICM.
447 if (getOptLevel() != CodeGenOpt::None) {
448 // FIXME: Re-enable coloring with register when it's capable of adding
451 PM.add(createStackSlotColoringPass(false));
453 // Run post-ra machine LICM to hoist reloads / remats.
454 if (!DisablePostRAMachineLICM)
455 PM.add(createMachineLICMPass(false));
457 printAndVerify("After StackSlotColoring and postra Machine LICM");
460 // Run post-ra passes.
461 if (addPostRegAlloc())
462 printAndVerify("After PostRegAlloc passes");
464 // Insert prolog/epilog code. Eliminate abstract frame index references...
465 PM.add(createPrologEpilogCodeInserter());
466 printAndVerify("After PrologEpilogCodeInserter");
468 // Branch folding must be run after regalloc and prolog/epilog insertion.
469 if (getOptLevel() != CodeGenOpt::None && !DisableBranchFold) {
470 PM.add(createBranchFoldingPass(getEnableTailMergeDefault()));
471 printNoVerify("After BranchFolding");
475 if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) {
476 PM.add(createTailDuplicatePass(false));
477 printNoVerify("After TailDuplicate");
481 if (getOptLevel() != CodeGenOpt::None && !DisableCopyProp) {
482 PM.add(createMachineCopyPropagationPass());
483 printNoVerify("After copy propagation pass");
486 // Expand pseudo instructions before second scheduling pass.
487 PM.add(createExpandPostRAPseudosPass());
488 printNoVerify("After ExpandPostRAPseudos");
490 // Run pre-sched2 passes.
492 printNoVerify("After PreSched2 passes");
494 // Second pass scheduler.
495 if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) {
496 PM.add(createPostRAScheduler(getOptLevel()));
497 printNoVerify("After PostRAScheduler");
500 PM.add(createGCMachineCodeAnalysisPass());
503 PM.add(createGCInfoPrinter(dbgs()));
505 if (getOptLevel() != CodeGenOpt::None && !DisableCodePlace) {
506 if (EnableBlockPlacement) {
507 // MachineBlockPlacement is an experimental pass which is disabled by
508 // default currently. Eventually it should subsume CodePlacementOpt, so
509 // when enabled, the other is disabled.
510 PM.add(createMachineBlockPlacementPass());
511 printNoVerify("After MachineBlockPlacement");
513 PM.add(createCodePlacementOptPass());
514 printNoVerify("After CodePlacementOpt");
517 // Run a separate pass to collect block placement statistics.
518 if (EnableBlockPlacementStats) {
519 PM.add(createMachineBlockPlacementStatsPass());
520 printNoVerify("After MachineBlockPlacementStats");
524 if (addPreEmitPass())
525 printNoVerify("After PreEmit passes");