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