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> 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)); 88 89 static cl::opt<cl::boolOrDefault> 90 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 91 cl::init(cl::BOU_UNSET)); 92 93 static bool getVerboseAsm() { 94 switch (AsmVerbose) { 95 default: 96 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 97 case cl::BOU_TRUE: return true; 98 case cl::BOU_FALSE: return false; 99 } 100 } 101 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")); 108 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!"); 124 } 125 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)) 133 return true; 134 assert(Context != 0 && "Failed to get MCContext"); 135 136 if (hasMCSaveTempLabels()) 137 Context->setAllowTemporaryLabels(false); 138 139 const MCAsmInfo &MAI = *getMCAsmInfo(); 140 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 141 OwningPtr<MCStreamer> AsmStreamer; 142 143 switch (FileType) { 144 default: return true; 145 case CGFT_AssemblyFile: { 146 MCInstPrinter *InstPrinter = 147 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI, STI); 148 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()); 156 } 157 158 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out, 159 getVerboseAsm(), 160 hasMCUseLoc(), 161 hasMCUseCFI(), 162 hasMCUseDwarfDirectory(), 163 InstPrinter, 164 MCE, MAB, 165 ShowMCInst); 166 AsmStreamer.reset(S); 167 break; 168 } 169 case CGFT_ObjectFile: { 170 // Create the code emitter for the target if it exists. If not, .o file 171 // emission fails. 172 MCCodeEmitter *MCE = getTarget().createMCCodeEmitter(*getInstrInfo(), STI, 173 *Context); 174 MCAsmBackend *MAB = getTarget().createMCAsmBackend(getTargetTriple()); 175 if (MCE == 0 || MAB == 0) 176 return true; 177 178 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), 179 *Context, *MAB, Out, 180 MCE, hasMCRelaxAll(), 181 hasMCNoExecStack())); 182 AsmStreamer.get()->InitSections(); 183 break; 184 } 185 case CGFT_Null: 186 // The Null output is intended for use for performance analysis and testing, 187 // not real users. 188 AsmStreamer.reset(createNullStreamer(*Context)); 189 break; 190 } 191 192 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 193 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 194 if (Printer == 0) 195 return true; 196 197 // If successful, createAsmPrinter took ownership of AsmStreamer. 198 AsmStreamer.take(); 199 200 PM.add(Printer); 201 202 PM.add(createGCInfoDeleter()); 203 return false; 204 } 205 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 210 /// not supported. 211 /// 212 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, 213 JITCodeEmitter &JCE, 214 bool DisableVerify) { 215 // Add common CodeGen passes. 216 MCContext *Ctx = 0; 217 if (addCommonCodeGenPasses(PM, DisableVerify, Ctx)) 218 return true; 219 220 addCodeEmitter(PM, JCE); 221 PM.add(createGCInfoDeleter()); 222 223 return false; // success! 224 } 225 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. 230 /// 231 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, 232 MCContext *&Ctx, 233 raw_ostream &Out, 234 bool DisableVerify) { 235 // Add common CodeGen passes. 236 if (addCommonCodeGenPasses(PM, DisableVerify, Ctx)) 237 return true; 238 239 if (hasMCSaveTempLabels()) 240 Ctx->setAllowTemporaryLabels(false); 241 242 // Create the code emitter for the target if it exists. If not, .o file 243 // emission fails. 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) 248 return true; 249 250 OwningPtr<MCStreamer> AsmStreamer; 251 AsmStreamer.reset(getTarget().createMCObjectStreamer(getTargetTriple(), *Ctx, 252 *MAB, Out, MCE, 253 hasMCRelaxAll(), 254 hasMCNoExecStack())); 255 AsmStreamer.get()->InitSections(); 256 257 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 258 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 259 if (Printer == 0) 260 return true; 261 262 // If successful, createAsmPrinter took ownership of AsmStreamer. 263 AsmStreamer.take(); 264 265 PM.add(Printer); 266 267 return false; // success! 268 } 269 270 void LLVMTargetMachine::printNoVerify(PassManagerBase &PM, 271 const char *Banner) const { 272 if (Options.PrintMachineCode) 273 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 274 } 275 276 void LLVMTargetMachine::printAndVerify(PassManagerBase &PM, 277 const char *Banner) const { 278 if (Options.PrintMachineCode) 279 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 280 281 if (VerifyMachineCode) 282 PM.add(createMachineVerifierPass(Banner)); 283 } 284 285 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 286 /// emitting to assembly files or machine code output. 287 /// 288 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 289 bool DisableVerify, 290 MCContext *&OutContext) { 291 // Standard LLVM-Level Passes. 292 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()); 299 300 // Before running any passes, run the verifier to determine if the input 301 // coming from the front-end and/or optimizer is valid. 302 if (!DisableVerify) 303 PM.add(createVerifierPass()); 304 305 // Run loop strength reduction before anything else. 306 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) { 307 PM.add(createLoopStrengthReducePass(getTargetLowering())); 308 if (PrintLSR) 309 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 310 } 311 312 PM.add(createGCLoweringPass()); 313 314 // Make sure that no unreachable blocks are instruction selected. 315 PM.add(createUnreachableBlockEliminationPass()); 316 317 // Turn exception handling constructs into something the code generators can 318 // handle. 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())); 328 // FALLTHROUGH 329 case ExceptionHandling::DwarfCFI: 330 case ExceptionHandling::ARM: 331 case ExceptionHandling::Win64: 332 PM.add(createDwarfEHPass(this)); 333 break; 334 case ExceptionHandling::None: 335 PM.add(createLowerInvokePass(getTargetLowering())); 336 337 // The lower invoke pass may create unreachable code. Remove it. 338 PM.add(createUnreachableBlockEliminationPass()); 339 break; 340 } 341 342 if (getOptLevel() != CodeGenOpt::None && !DisableCGP) 343 PM.add(createCodeGenPreparePass(getTargetLowering())); 344 345 PM.add(createStackProtectorPass(getTargetLowering())); 346 347 addPreISel(PM); 348 349 if (PrintISelInput) 350 PM.add(createPrintFunctionPass("\n\n" 351 "*** Final LLVM Code input to ISel ***\n", 352 &dbgs())); 353 354 // All passes which modify the LLVM IR are now complete; run the verifier 355 // to ensure that the IR is valid. 356 if (!DisableVerify) 357 PM.add(createVerifierPass()); 358 359 // Standard Lower-Level Passes. 360 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(), 364 *getRegisterInfo(), 365 &getTargetLowering()->getObjFileLowering()); 366 PM.add(MMI); 367 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref. 368 369 // Set up a MachineFunction for the rest of CodeGen to work on. 370 PM.add(new MachineFunctionAnalysis(*this)); 371 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; 377 378 // Ask the target for an isel. 379 if (addInstSelector(PM)) 380 return true; 381 382 // Print the instruction selected machine code... 383 printAndVerify(PM, "After Instruction Selection"); 384 385 // Expand pseudo-instructions emitted by ISel. 386 PM.add(createExpandISelPseudosPass()); 387 388 // Pre-ra tail duplication. 389 if (getOptLevel() != CodeGenOpt::None && !DisableEarlyTailDup) { 390 PM.add(createTailDuplicatePass(true)); 391 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate"); 392 } 393 394 // Optimize PHIs before DCE: removing dead PHI cycles may make more 395 // instructions dead. 396 if (getOptLevel() != CodeGenOpt::None) 397 PM.add(createOptimizePHIsPass()); 398 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()); 402 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"); 411 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"); 419 420 PM.add(createPeepholeOptimizerPass()); 421 printAndVerify(PM, "After codegen peephole optimization pass"); 422 } 423 424 // Run pre-ra passes. 425 if (addPreRegAlloc(PM)) 426 printAndVerify(PM, "After PreRegAlloc passes"); 427 428 // Perform register allocation. 429 PM.add(createRegisterAllocator(getOptLevel())); 430 printAndVerify(PM, "After Register Allocation"); 431 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 435 // kill markers. 436 if (!DisableSSC) 437 PM.add(createStackSlotColoringPass(false)); 438 439 // Run post-ra machine LICM to hoist reloads / remats. 440 if (!DisablePostRAMachineLICM) 441 PM.add(createMachineLICMPass(false)); 442 443 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM"); 444 } 445 446 // Run post-ra passes. 447 if (addPostRegAlloc(PM)) 448 printAndVerify(PM, "After PostRegAlloc passes"); 449 450 // Insert prolog/epilog code. Eliminate abstract frame index references... 451 PM.add(createPrologEpilogCodeInserter()); 452 printAndVerify(PM, "After PrologEpilogCodeInserter"); 453 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"); 458 } 459 460 // Tail duplication. 461 if (getOptLevel() != CodeGenOpt::None && !DisableTailDuplicate) { 462 PM.add(createTailDuplicatePass(false)); 463 printNoVerify(PM, "After TailDuplicate"); 464 } 465 466 // Copy propagation. 467 if (getOptLevel() != CodeGenOpt::None) { 468 PM.add(createMachineCopyPropagationPass()); 469 printNoVerify(PM, "After copy propagation pass"); 470 } 471 472 // Expand pseudo instructions before second scheduling pass. 473 PM.add(createExpandPostRAPseudosPass()); 474 printNoVerify(PM, "After ExpandPostRAPseudos"); 475 476 // Run pre-sched2 passes. 477 if (addPreSched2(PM)) 478 printNoVerify(PM, "After PreSched2 passes"); 479 480 // Second pass scheduler. 481 if (getOptLevel() != CodeGenOpt::None && !DisablePostRA) { 482 PM.add(createPostRAScheduler(getOptLevel())); 483 printNoVerify(PM, "After PostRAScheduler"); 484 } 485 486 PM.add(createGCMachineCodeAnalysisPass()); 487 488 if (PrintGCInfo) 489 PM.add(createGCInfoPrinter(dbgs())); 490 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"); 498 } else { 499 PM.add(createCodePlacementOptPass()); 500 printNoVerify(PM, "After CodePlacementOpt"); 501 } 502 503 // Run a separate pass to collect block placement statistics. 504 if (EnableBlockPlacementStats) { 505 PM.add(createMachineBlockPlacementStatsPass()); 506 printNoVerify(PM, "After MachineBlockPlacementStats"); 507 } 508 } 509 510 if (addPreEmitPass(PM)) 511 printNoVerify(PM, "After PreEmit passes"); 512 513 return false; 514 } 515