LLVMTargetMachine.cpp revision ca30f75703fa4f032b256bba445608c79e2bd82c
1//===-- LLVMTargetMachine.cpp - Implement the LLVMTargetMachine class -----===// 2// 3// The LLVM Compiler Infrastructure 4// 5// This file is distributed under the University of Illinois Open Source 6// License. See LICENSE.TXT for details. 7// 8//===----------------------------------------------------------------------===// 9// 10// This file implements the LLVMTargetMachine class. 11// 12//===----------------------------------------------------------------------===// 13 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" 42using namespace llvm; 43 44namespace llvm { 45 bool EnableFastISel; 46} 47 48static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, 49 cl::desc("Disable Post Regalloc")); 50static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 51 cl::desc("Disable branch folding")); 52static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 53 cl::desc("Disable tail duplication")); 54static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 55 cl::desc("Disable pre-register allocation tail duplication")); 56static cl::opt<bool> EnableBlockPlacement("enable-block-placement", 57 cl::Hidden, cl::desc("Enable probability-driven block placement")); 58static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, 59 cl::desc("Disable code placement")); 60static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 61 cl::desc("Disable Stack Slot Coloring")); 62static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden, 63 cl::desc("Disable Machine Dead Code Elimination")); 64static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 65 cl::desc("Disable Machine LICM")); 66static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden, 67 cl::desc("Disable Machine Common Subexpression Elimination")); 68static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 69 cl::Hidden, 70 cl::desc("Disable Machine LICM")); 71static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 72 cl::desc("Disable Machine Sinking")); 73static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 74 cl::desc("Disable Loop Strength Reduction Pass")); 75static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 76 cl::desc("Disable Codegen Prepare")); 77static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 78 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 79static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 80 cl::desc("Print LLVM IR input to isel pass")); 81static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 82 cl::desc("Dump garbage collector data")); 83static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 84 cl::desc("Show encoding in .s output")); 85static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden, 86 cl::desc("Show instruction structure in .s output")); 87static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden, 88 cl::desc("Enable MC API logging")); 89static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 90 cl::desc("Verify generated machine code"), 91 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); 92 93static cl::opt<cl::boolOrDefault> 94AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 95 cl::init(cl::BOU_UNSET)); 96 97static bool getVerboseAsm() { 98 switch (AsmVerbose) { 99 default: 100 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 101 case cl::BOU_TRUE: return true; 102 case cl::BOU_FALSE: return false; 103 } 104} 105 106// Enable or disable FastISel. Both options are needed, because 107// FastISel is enabled by default with -fast, and we wish to be 108// able to enable or disable fast-isel independently from -O0. 109static cl::opt<cl::boolOrDefault> 110EnableFastISelOption("fast-isel", cl::Hidden, 111 cl::desc("Enable the \"fast\" instruction selector")); 112 113LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple, 114 StringRef CPU, StringRef FS, 115 Reloc::Model RM, CodeModel::Model CM) 116 : TargetMachine(T, Triple, CPU, FS) { 117 CodeGenInfo = T.createMCCodeGenInfo(Triple, RM, CM); 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!"); 126} 127 128bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM, 129 formatted_raw_ostream &Out, 130 CodeGenFileType FileType, 131 CodeGenOpt::Level OptLevel, 132 bool DisableVerify) { 133 // Add common CodeGen passes. 134 MCContext *Context = 0; 135 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context)) 136 return true; 137 assert(Context != 0 && "Failed to get MCContext"); 138 139 if (hasMCSaveTempLabels()) 140 Context->setAllowTemporaryLabels(false); 141 142 const MCAsmInfo &MAI = *getMCAsmInfo(); 143 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 144 OwningPtr<MCStreamer> AsmStreamer; 145 146 switch (FileType) { 147 default: return true; 148 case CGFT_AssemblyFile: { 149 MCInstPrinter *InstPrinter = 150 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI); 151 152 // Create a code emitter if asked to show the encoding. 153 MCCodeEmitter *MCE = 0; 154 MCAsmBackend *MAB = 0; 155 if (ShowMCEncoding) { 156 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 157 MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, *Context); 158 MAB = getTarget().createMCAsmBackend(getTargetTriple()); 159 } 160 161 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out, 162 getVerboseAsm(), 163 hasMCUseLoc(), 164 hasMCUseCFI(), 165 hasMCUseDwarfDirectory(), 166 InstPrinter, 167 MCE, MAB, 168 ShowMCInst); 169 AsmStreamer.reset(S); 170 break; 171 } 172 case CGFT_ObjectFile: { 173 // Create the code emitter for the target if it exists. If not, .o file 174 // emission fails. 175 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, 176 *Context); 177 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple()); 178 if (MCE == 0 || MAB == 0) 179 return true; 180 181 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), 182 *Context, *MAB, Out, 183 MCE, hasMCRelaxAll(), 184 hasMCNoExecStack())); 185 AsmStreamer.get()->InitSections(); 186 break; 187 } 188 case CGFT_Null: 189 // The Null output is intended for use for performance analysis and testing, 190 // not real users. 191 AsmStreamer.reset(createNullStreamer(*Context)); 192 break; 193 } 194 195 if (EnableMCLogging) 196 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs())); 197 198 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 199 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 200 if (Printer == 0) 201 return true; 202 203 // If successful, createAsmPrinter took ownership of AsmStreamer. 204 AsmStreamer.take(); 205 206 PM.add(Printer); 207 208 PM.add(createGCInfoDeleter()); 209 return false; 210} 211 212/// addPassesToEmitMachineCode - Add passes to the specified pass manager to 213/// get machine code emitted. This uses a JITCodeEmitter object to handle 214/// actually outputting the machine code and resolving things like the address 215/// of functions. This method should returns true if machine code emission is 216/// not supported. 217/// 218bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, 219 JITCodeEmitter &JCE, 220 CodeGenOpt::Level OptLevel, 221 bool DisableVerify) { 222 // Add common CodeGen passes. 223 MCContext *Ctx = 0; 224 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 225 return true; 226 227 addCodeEmitter(PM, OptLevel, JCE); 228 PM.add(createGCInfoDeleter()); 229 230 return false; // success! 231} 232 233/// addPassesToEmitMC - Add passes to the specified pass manager to get 234/// machine code emitted with the MCJIT. This method returns true if machine 235/// code is not supported. It fills the MCContext Ctx pointer which can be 236/// used to build custom MCStreamer. 237/// 238bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, 239 MCContext *&Ctx, 240 raw_ostream &Out, 241 CodeGenOpt::Level OptLevel, 242 bool DisableVerify) { 243 // Add common CodeGen passes. 244 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 245 return true; 246 247 if (hasMCSaveTempLabels()) 248 Ctx->setAllowTemporaryLabels(false); 249 250 // Create the code emitter for the target if it exists. If not, .o file 251 // emission fails. 252 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 253 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(),STI, *Ctx); 254 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple()); 255 if (MCE == 0 || MAB == 0) 256 return true; 257 258 OwningPtr<MCStreamer> AsmStreamer; 259 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx, 260 *MAB, Out, MCE, 261 hasMCRelaxAll(), 262 hasMCNoExecStack())); 263 AsmStreamer.get()->InitSections(); 264 265 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 266 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 267 if (Printer == 0) 268 return true; 269 270 // If successful, createAsmPrinter took ownership of AsmStreamer. 271 AsmStreamer.take(); 272 273 PM.add(Printer); 274 275 return false; // success! 276} 277 278static void printNoVerify(PassManagerBase &PM, const char *Banner) { 279 if (PrintMachineCode) 280 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 281} 282 283static void printAndVerify(PassManagerBase &PM, 284 const char *Banner) { 285 if (PrintMachineCode) 286 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 287 288 if (VerifyMachineCode) 289 PM.add(createMachineVerifierPass(Banner)); 290} 291 292/// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 293/// emitting to assembly files or machine code output. 294/// 295bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 296 CodeGenOpt::Level OptLevel, 297 bool DisableVerify, 298 MCContext *&OutContext) { 299 // Standard LLVM-Level Passes. 300 301 // Basic AliasAnalysis support. 302 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 303 // BasicAliasAnalysis wins if they disagree. This is intended to help 304 // support "obvious" type-punning idioms. 305 PM.add(createTypeBasedAliasAnalysisPass()); 306 PM.add(createBasicAliasAnalysisPass()); 307 308 // Before running any passes, run the verifier to determine if the input 309 // coming from the front-end and/or optimizer is valid. 310 if (!DisableVerify) 311 PM.add(createVerifierPass()); 312 313 // Run loop strength reduction before anything else. 314 if (OptLevel != CodeGenOpt::None && !DisableLSR) { 315 PM.add(createLoopStrengthReducePass(getTargetLowering())); 316 if (PrintLSR) 317 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 318 } 319 320 PM.add(createGCLoweringPass()); 321 322 // Make sure that no unreachable blocks are instruction selected. 323 PM.add(createUnreachableBlockEliminationPass()); 324 325 // Turn exception handling constructs into something the code generators can 326 // handle. 327 switch (getMCAsmInfo()->getExceptionHandlingType()) { 328 case ExceptionHandling::SjLj: 329 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 330 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 331 // catch info can get misplaced when a selector ends up more than one block 332 // removed from the parent invoke(s). This could happen when a landing 333 // pad is shared by multiple invokes and is also a target of a normal 334 // edge from elsewhere. 335 PM.add(createSjLjEHPass(getTargetLowering())); 336 // FALLTHROUGH 337 case ExceptionHandling::DwarfCFI: 338 case ExceptionHandling::ARM: 339 case ExceptionHandling::Win64: 340 PM.add(createDwarfEHPass(this)); 341 break; 342 case ExceptionHandling::None: 343 PM.add(createLowerInvokePass(getTargetLowering())); 344 345 // The lower invoke pass may create unreachable code. Remove it. 346 PM.add(createUnreachableBlockEliminationPass()); 347 break; 348 } 349 350 if (OptLevel != CodeGenOpt::None && !DisableCGP) 351 PM.add(createCodeGenPreparePass(getTargetLowering())); 352 353 PM.add(createStackProtectorPass(getTargetLowering())); 354 355 addPreISel(PM, OptLevel); 356 357 if (PrintISelInput) 358 PM.add(createPrintFunctionPass("\n\n" 359 "*** Final LLVM Code input to ISel ***\n", 360 &dbgs())); 361 362 // All passes which modify the LLVM IR are now complete; run the verifier 363 // to ensure that the IR is valid. 364 if (!DisableVerify) 365 PM.add(createVerifierPass()); 366 367 // Standard Lower-Level Passes. 368 369 // Install a MachineModuleInfo class, which is an immutable pass that holds 370 // all the per-module stuff we're generating, including MCContext. 371 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), 372 *getRegisterInfo(), 373 &getTargetLowering()->getObjFileLowering()); 374 PM.add(MMI); 375 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref. 376 377 // Set up a MachineFunction for the rest of CodeGen to work on. 378 PM.add(new MachineFunctionAnalysis(*this, OptLevel)); 379 380 // Enable FastISel with -fast, but allow that to be overridden. 381 if (EnableFastISelOption == cl::BOU_TRUE || 382 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE)) 383 EnableFastISel = true; 384 385 // Ask the target for an isel. 386 if (addInstSelector(PM, OptLevel)) 387 return true; 388 389 // Print the instruction selected machine code... 390 printAndVerify(PM, "After Instruction Selection"); 391 392 // Expand pseudo-instructions emitted by ISel. 393 PM.add(createExpandISelPseudosPass()); 394 395 // Pre-ra tail duplication. 396 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) { 397 PM.add(createTailDuplicatePass(true)); 398 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate"); 399 } 400 401 // Optimize PHIs before DCE: removing dead PHI cycles may make more 402 // instructions dead. 403 if (OptLevel != CodeGenOpt::None) 404 PM.add(createOptimizePHIsPass()); 405 406 // If the target requests it, assign local variables to stack slots relative 407 // to one another and simplify frame index references where possible. 408 PM.add(createLocalStackSlotAllocationPass()); 409 410 if (OptLevel != CodeGenOpt::None) { 411 // With optimization, dead code should already be eliminated. However 412 // there is one known exception: lowered code for arguments that are only 413 // used by tail calls, where the tail calls reuse the incoming stack 414 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 415 if (!DisableMachineDCE) 416 PM.add(createDeadMachineInstructionElimPass()); 417 printAndVerify(PM, "After codegen DCE pass"); 418 419 if (!DisableMachineLICM) 420 PM.add(createMachineLICMPass()); 421 if (!DisableMachineCSE) 422 PM.add(createMachineCSEPass()); 423 if (!DisableMachineSink) 424 PM.add(createMachineSinkingPass()); 425 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes"); 426 427 PM.add(createPeepholeOptimizerPass()); 428 printAndVerify(PM, "After codegen peephole optimization pass"); 429 } 430 431 // Run pre-ra passes. 432 if (addPreRegAlloc(PM, OptLevel)) 433 printAndVerify(PM, "After PreRegAlloc passes"); 434 435 // Perform register allocation. 436 PM.add(createRegisterAllocator(OptLevel)); 437 printAndVerify(PM, "After Register Allocation"); 438 439 // Perform stack slot coloring and post-ra machine LICM. 440 if (OptLevel != CodeGenOpt::None) { 441 // FIXME: Re-enable coloring with register when it's capable of adding 442 // kill markers. 443 if (!DisableSSC) 444 PM.add(createStackSlotColoringPass(false)); 445 446 // Run post-ra machine LICM to hoist reloads / remats. 447 if (!DisablePostRAMachineLICM) 448 PM.add(createMachineLICMPass(false)); 449 450 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM"); 451 } 452 453 // Run post-ra passes. 454 if (addPostRegAlloc(PM, OptLevel)) 455 printAndVerify(PM, "After PostRegAlloc passes"); 456 457 PM.add(createExpandPostRAPseudosPass()); 458 printAndVerify(PM, "After ExpandPostRAPseudos"); 459 460 // Insert prolog/epilog code. Eliminate abstract frame index references... 461 PM.add(createPrologEpilogCodeInserter()); 462 printAndVerify(PM, "After PrologEpilogCodeInserter"); 463 464 // Run pre-sched2 passes. 465 if (addPreSched2(PM, OptLevel)) 466 printAndVerify(PM, "After PreSched2 passes"); 467 468 // Second pass scheduler. 469 if (OptLevel != CodeGenOpt::None && !DisablePostRA) { 470 PM.add(createPostRAScheduler(OptLevel)); 471 printAndVerify(PM, "After PostRAScheduler"); 472 } 473 474 // Branch folding must be run after regalloc and prolog/epilog insertion. 475 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) { 476 PM.add(createBranchFoldingPass(getEnableTailMergeDefault())); 477 printNoVerify(PM, "After BranchFolding"); 478 } 479 480 // Tail duplication. 481 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { 482 PM.add(createTailDuplicatePass(false)); 483 printNoVerify(PM, "After TailDuplicate"); 484 } 485 486 PM.add(createGCMachineCodeAnalysisPass()); 487 488 if (PrintGCInfo) 489 PM.add(createGCInfoPrinter(dbgs())); 490 491 if (OptLevel != 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"); 498 } else { 499 PM.add(createCodePlacementOptPass()); 500 printNoVerify(PM, "After CodePlacementOpt"); 501 } 502 } 503 504 if (addPreEmitPass(PM, OptLevel)) 505 printNoVerify(PM, "After PreEmit passes"); 506 507 return false; 508} 509