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/TargetAsmInfo.h" 31 #include "llvm/Target/TargetData.h" 32 #include "llvm/Target/TargetInstrInfo.h" 33 #include "llvm/Target/TargetRegistry.h" 34 #include "llvm/Target/TargetSubtargetInfo.h" 35 #include "llvm/Transforms/Scalar.h" 36 #include "llvm/ADT/OwningPtr.h" 37 #include "llvm/Support/CommandLine.h" 38 #include "llvm/Support/Debug.h" 39 #include "llvm/Support/FormattedStream.h" 40 using namespace llvm; 41 42 namespace llvm { 43 bool EnableFastISel; 44 } 45 46 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, 47 cl::desc("Disable Post Regalloc")); 48 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 49 cl::desc("Disable branch folding")); 50 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 51 cl::desc("Disable tail duplication")); 52 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 53 cl::desc("Disable pre-register allocation tail duplication")); 54 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, 55 cl::desc("Disable code placement")); 56 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 57 cl::desc("Disable Stack Slot Coloring")); 58 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 59 cl::desc("Disable Machine LICM")); 60 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 61 cl::Hidden, 62 cl::desc("Disable Machine LICM")); 63 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 64 cl::desc("Disable Machine Sinking")); 65 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 66 cl::desc("Disable Loop Strength Reduction Pass")); 67 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 68 cl::desc("Disable Codegen Prepare")); 69 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 70 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 71 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 72 cl::desc("Print LLVM IR input to isel pass")); 73 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 74 cl::desc("Dump garbage collector data")); 75 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 76 cl::desc("Show encoding in .s output")); 77 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden, 78 cl::desc("Show instruction structure in .s output")); 79 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden, 80 cl::desc("Enable MC API logging")); 81 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 82 cl::desc("Verify generated machine code"), 83 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); 84 85 static cl::opt<cl::boolOrDefault> 86 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 87 cl::init(cl::BOU_UNSET)); 88 89 static bool getVerboseAsm() { 90 switch (AsmVerbose) { 91 default: 92 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 93 case cl::BOU_TRUE: return true; 94 case cl::BOU_FALSE: return false; 95 } 96 } 97 98 // Enable or disable FastISel. Both options are needed, because 99 // FastISel is enabled by default with -fast, and we wish to be 100 // able to enable or disable fast-isel independently from -O0. 101 static cl::opt<cl::boolOrDefault> 102 EnableFastISelOption("fast-isel", cl::Hidden, 103 cl::desc("Enable the \"fast\" instruction selector")); 104 105 LLVMTargetMachine::LLVMTargetMachine(const Target &T, StringRef Triple, 106 StringRef CPU, StringRef FS) 107 : TargetMachine(T, Triple, CPU, FS) { 108 AsmInfo = T.createMCAsmInfo(Triple); 109 } 110 111 // Set the default code model for the JIT for a generic target. 112 // FIXME: Is small right here? or .is64Bit() ? Large : Small? 113 void LLVMTargetMachine::setCodeModelForJIT() { 114 setCodeModel(CodeModel::Small); 115 } 116 117 // Set the default code model for static compilation for a generic target. 118 void LLVMTargetMachine::setCodeModelForStatic() { 119 setCodeModel(CodeModel::Small); 120 } 121 122 bool LLVMTargetMachine::addPassesToEmitFile(PassManagerBase &PM, 123 formatted_raw_ostream &Out, 124 CodeGenFileType FileType, 125 CodeGenOpt::Level OptLevel, 126 bool DisableVerify) { 127 // Add common CodeGen passes. 128 MCContext *Context = 0; 129 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Context)) 130 return true; 131 assert(Context != 0 && "Failed to get MCContext"); 132 133 if (hasMCSaveTempLabels()) 134 Context->setAllowTemporaryLabels(false); 135 136 const MCAsmInfo &MAI = *getMCAsmInfo(); 137 OwningPtr<MCStreamer> AsmStreamer; 138 139 switch (FileType) { 140 default: return true; 141 case CGFT_AssemblyFile: { 142 MCInstPrinter *InstPrinter = 143 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI); 144 145 // Create a code emitter if asked to show the encoding. 146 MCCodeEmitter *MCE = 0; 147 TargetAsmBackend *TAB = 0; 148 if (ShowMCEncoding) { 149 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 150 MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI, *Context); 151 TAB = getTarget().createAsmBackend(getTargetTriple()); 152 } 153 154 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out, 155 getVerboseAsm(), 156 hasMCUseLoc(), 157 hasMCUseCFI(), 158 InstPrinter, 159 MCE, TAB, 160 ShowMCInst); 161 AsmStreamer.reset(S); 162 break; 163 } 164 case CGFT_ObjectFile: { 165 // Create the code emitter for the target if it exists. If not, .o file 166 // emission fails. 167 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 168 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(), STI, 169 *Context); 170 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple()); 171 if (MCE == 0 || TAB == 0) 172 return true; 173 174 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(), 175 *Context, *TAB, Out, MCE, 176 hasMCRelaxAll(), 177 hasMCNoExecStack())); 178 AsmStreamer.get()->InitSections(); 179 break; 180 } 181 case CGFT_Null: 182 // The Null output is intended for use for performance analysis and testing, 183 // not real users. 184 AsmStreamer.reset(createNullStreamer(*Context)); 185 break; 186 } 187 188 if (EnableMCLogging) 189 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs())); 190 191 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 192 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 193 if (Printer == 0) 194 return true; 195 196 // If successful, createAsmPrinter took ownership of AsmStreamer. 197 AsmStreamer.take(); 198 199 PM.add(Printer); 200 201 // Make sure the code model is set. 202 setCodeModelForStatic(); 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 CodeGenOpt::Level OptLevel, 216 bool DisableVerify) { 217 // Make sure the code model is set. 218 setCodeModelForJIT(); 219 220 // Add common CodeGen passes. 221 MCContext *Ctx = 0; 222 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 223 return true; 224 225 addCodeEmitter(PM, OptLevel, JCE); 226 PM.add(createGCInfoDeleter()); 227 228 return false; // success! 229 } 230 231 /// addPassesToEmitMC - Add passes to the specified pass manager to get 232 /// machine code emitted with the MCJIT. This method returns true if machine 233 /// code is not supported. It fills the MCContext Ctx pointer which can be 234 /// used to build custom MCStreamer. 235 /// 236 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, 237 MCContext *&Ctx, 238 raw_ostream &Out, 239 CodeGenOpt::Level OptLevel, 240 bool DisableVerify) { 241 // Add common CodeGen passes. 242 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 243 return true; 244 245 if (hasMCSaveTempLabels()) 246 Ctx->setAllowTemporaryLabels(false); 247 248 // Create the code emitter for the target if it exists. If not, .o file 249 // emission fails. 250 const MCSubtargetInfo &STI = getSubtarget<MCSubtargetInfo>(); 251 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*getInstrInfo(),STI, *Ctx); 252 TargetAsmBackend *TAB = getTarget().createAsmBackend(getTargetTriple()); 253 if (MCE == 0 || TAB == 0) 254 return true; 255 256 OwningPtr<MCStreamer> AsmStreamer; 257 AsmStreamer.reset(getTarget().createObjectStreamer(getTargetTriple(), *Ctx, 258 *TAB, Out, MCE, 259 hasMCRelaxAll(), 260 hasMCNoExecStack())); 261 AsmStreamer.get()->InitSections(); 262 263 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 264 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 265 if (Printer == 0) 266 return true; 267 268 // If successful, createAsmPrinter took ownership of AsmStreamer. 269 AsmStreamer.take(); 270 271 PM.add(Printer); 272 273 // Make sure the code model is set. 274 setCodeModelForJIT(); 275 276 return false; // success! 277 } 278 279 static void printNoVerify(PassManagerBase &PM, const char *Banner) { 280 if (PrintMachineCode) 281 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 282 } 283 284 static void printAndVerify(PassManagerBase &PM, 285 const char *Banner) { 286 if (PrintMachineCode) 287 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 288 289 if (VerifyMachineCode) 290 PM.add(createMachineVerifierPass(Banner)); 291 } 292 293 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 294 /// emitting to assembly files or machine code output. 295 /// 296 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 297 CodeGenOpt::Level OptLevel, 298 bool DisableVerify, 299 MCContext *&OutContext) { 300 // Standard LLVM-Level Passes. 301 302 // Basic AliasAnalysis support. 303 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 304 // BasicAliasAnalysis wins if they disagree. This is intended to help 305 // support "obvious" type-punning idioms. 306 PM.add(createTypeBasedAliasAnalysisPass()); 307 PM.add(createBasicAliasAnalysisPass()); 308 309 // Before running any passes, run the verifier to determine if the input 310 // coming from the front-end and/or optimizer is valid. 311 if (!DisableVerify) 312 PM.add(createVerifierPass()); 313 314 // Run loop strength reduction before anything else. 315 if (OptLevel != CodeGenOpt::None && !DisableLSR) { 316 PM.add(createLoopStrengthReducePass(getTargetLowering())); 317 if (PrintLSR) 318 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 319 } 320 321 PM.add(createGCLoweringPass()); 322 323 // Make sure that no unreachable blocks are instruction selected. 324 PM.add(createUnreachableBlockEliminationPass()); 325 326 // Turn exception handling constructs into something the code generators can 327 // handle. 328 switch (getMCAsmInfo()->getExceptionHandlingType()) { 329 case ExceptionHandling::SjLj: 330 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 331 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 332 // catch info can get misplaced when a selector ends up more than one block 333 // removed from the parent invoke(s). This could happen when a landing 334 // pad is shared by multiple invokes and is also a target of a normal 335 // edge from elsewhere. 336 PM.add(createSjLjEHPass(getTargetLowering())); 337 // FALLTHROUGH 338 case ExceptionHandling::DwarfCFI: 339 case ExceptionHandling::ARM: 340 case ExceptionHandling::Win64: 341 PM.add(createDwarfEHPass(this)); 342 break; 343 case ExceptionHandling::None: 344 PM.add(createLowerInvokePass(getTargetLowering())); 345 346 // The lower invoke pass may create unreachable code. Remove it. 347 PM.add(createUnreachableBlockEliminationPass()); 348 break; 349 } 350 351 if (OptLevel != CodeGenOpt::None && !DisableCGP) 352 PM.add(createCodeGenPreparePass(getTargetLowering())); 353 354 PM.add(createStackProtectorPass(getTargetLowering())); 355 356 addPreISel(PM, OptLevel); 357 358 if (PrintISelInput) 359 PM.add(createPrintFunctionPass("\n\n" 360 "*** Final LLVM Code input to ISel ***\n", 361 &dbgs())); 362 363 // All passes which modify the LLVM IR are now complete; run the verifier 364 // to ensure that the IR is valid. 365 if (!DisableVerify) 366 PM.add(createVerifierPass()); 367 368 // Standard Lower-Level Passes. 369 370 // Install a MachineModuleInfo class, which is an immutable pass that holds 371 // all the per-module stuff we're generating, including MCContext. 372 TargetAsmInfo *TAI = new TargetAsmInfo(*this); 373 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI); 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 PM.add(createDeadMachineInstructionElimPass()); 416 printAndVerify(PM, "After codegen DCE pass"); 417 418 if (!DisableMachineLICM) 419 PM.add(createMachineLICMPass()); 420 PM.add(createMachineCSEPass()); 421 if (!DisableMachineSink) 422 PM.add(createMachineSinkingPass()); 423 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes"); 424 425 PM.add(createPeepholeOptimizerPass()); 426 printAndVerify(PM, "After codegen peephole optimization pass"); 427 } 428 429 // Run pre-ra passes. 430 if (addPreRegAlloc(PM, OptLevel)) 431 printAndVerify(PM, "After PreRegAlloc passes"); 432 433 // Perform register allocation. 434 PM.add(createRegisterAllocator(OptLevel)); 435 printAndVerify(PM, "After Register Allocation"); 436 437 // Perform stack slot coloring and post-ra machine LICM. 438 if (OptLevel != CodeGenOpt::None) { 439 // FIXME: Re-enable coloring with register when it's capable of adding 440 // kill markers. 441 if (!DisableSSC) 442 PM.add(createStackSlotColoringPass(false)); 443 444 // Run post-ra machine LICM to hoist reloads / remats. 445 if (!DisablePostRAMachineLICM) 446 PM.add(createMachineLICMPass(false)); 447 448 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM"); 449 } 450 451 // Run post-ra passes. 452 if (addPostRegAlloc(PM, OptLevel)) 453 printAndVerify(PM, "After PostRegAlloc passes"); 454 455 PM.add(createLowerSubregsPass()); 456 printAndVerify(PM, "After LowerSubregs"); 457 458 // Insert prolog/epilog code. Eliminate abstract frame index references... 459 PM.add(createPrologEpilogCodeInserter()); 460 printAndVerify(PM, "After PrologEpilogCodeInserter"); 461 462 // Run pre-sched2 passes. 463 if (addPreSched2(PM, OptLevel)) 464 printAndVerify(PM, "After PreSched2 passes"); 465 466 // Second pass scheduler. 467 if (OptLevel != CodeGenOpt::None && !DisablePostRA) { 468 PM.add(createPostRAScheduler(OptLevel)); 469 printAndVerify(PM, "After PostRAScheduler"); 470 } 471 472 // Branch folding must be run after regalloc and prolog/epilog insertion. 473 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) { 474 PM.add(createBranchFoldingPass(getEnableTailMergeDefault())); 475 printNoVerify(PM, "After BranchFolding"); 476 } 477 478 // Tail duplication. 479 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { 480 PM.add(createTailDuplicatePass(false)); 481 printNoVerify(PM, "After TailDuplicate"); 482 } 483 484 PM.add(createGCMachineCodeAnalysisPass()); 485 486 if (PrintGCInfo) 487 PM.add(createGCInfoPrinter(dbgs())); 488 489 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) { 490 PM.add(createCodePlacementOptPass()); 491 printNoVerify(PM, "After CodePlacementOpt"); 492 } 493 494 if (addPreEmitPass(PM, OptLevel)) 495 printNoVerify(PM, "After PreEmit passes"); 496 497 return false; 498 } 499