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