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