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/Verifier.h" 17 #include "llvm/Assembly/PrintModulePass.h" 18 #include "llvm/CodeGen/AsmPrinter.h" 19 #include "llvm/CodeGen/MachineFunctionAnalysis.h" 20 #include "llvm/CodeGen/MachineModuleInfo.h" 21 #include "llvm/CodeGen/GCStrategy.h" 22 #include "llvm/CodeGen/Passes.h" 23 #include "llvm/Target/TargetLowering.h" 24 #include "llvm/Target/TargetOptions.h" 25 #include "llvm/MC/MCAsmInfo.h" 26 #include "llvm/MC/MCStreamer.h" 27 #include "llvm/Target/TargetAsmInfo.h" 28 #include "llvm/Target/TargetData.h" 29 #include "llvm/Target/TargetRegistry.h" 30 #include "llvm/Transforms/Scalar.h" 31 #include "llvm/ADT/OwningPtr.h" 32 #include "llvm/Support/CommandLine.h" 33 #include "llvm/Support/Debug.h" 34 #include "llvm/Support/FormattedStream.h" 35 #include "llvm/Support/StandardPasses.h" 36 using namespace llvm; 37 38 namespace llvm { 39 bool EnableFastISel; 40 } 41 42 static cl::opt<bool> DisablePostRA("disable-post-ra", cl::Hidden, 43 cl::desc("Disable Post Regalloc")); 44 static cl::opt<bool> DisableBranchFold("disable-branch-fold", cl::Hidden, 45 cl::desc("Disable branch folding")); 46 static cl::opt<bool> DisableTailDuplicate("disable-tail-duplicate", cl::Hidden, 47 cl::desc("Disable tail duplication")); 48 static cl::opt<bool> DisableEarlyTailDup("disable-early-taildup", cl::Hidden, 49 cl::desc("Disable pre-register allocation tail duplication")); 50 static cl::opt<bool> DisableCodePlace("disable-code-place", cl::Hidden, 51 cl::desc("Disable code placement")); 52 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 53 cl::desc("Disable Stack Slot Coloring")); 54 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 55 cl::desc("Disable Machine LICM")); 56 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 57 cl::Hidden, 58 cl::desc("Disable Machine LICM")); 59 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 60 cl::desc("Disable Machine Sinking")); 61 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 62 cl::desc("Disable Loop Strength Reduction Pass")); 63 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 64 cl::desc("Disable Codegen Prepare")); 65 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 66 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 67 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 68 cl::desc("Print LLVM IR input to isel pass")); 69 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 70 cl::desc("Dump garbage collector data")); 71 static cl::opt<bool> ShowMCEncoding("show-mc-encoding", cl::Hidden, 72 cl::desc("Show encoding in .s output")); 73 static cl::opt<bool> ShowMCInst("show-mc-inst", cl::Hidden, 74 cl::desc("Show instruction structure in .s output")); 75 static cl::opt<bool> EnableMCLogging("enable-mc-api-logging", cl::Hidden, 76 cl::desc("Enable MC API logging")); 77 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 78 cl::desc("Verify generated machine code"), 79 cl::init(getenv("LLVM_VERIFY_MACHINEINSTRS")!=NULL)); 80 81 static cl::opt<cl::boolOrDefault> 82 AsmVerbose("asm-verbose", cl::desc("Add comments to directives."), 83 cl::init(cl::BOU_UNSET)); 84 85 static bool getVerboseAsm() { 86 switch (AsmVerbose) { 87 default: 88 case cl::BOU_UNSET: return TargetMachine::getAsmVerbosityDefault(); 89 case cl::BOU_TRUE: return true; 90 case cl::BOU_FALSE: return false; 91 } 92 } 93 94 // Enable or disable FastISel. Both options are needed, because 95 // FastISel is enabled by default with -fast, and we wish to be 96 // able to enable or disable fast-isel independently from -O0. 97 static cl::opt<cl::boolOrDefault> 98 EnableFastISelOption("fast-isel", cl::Hidden, 99 cl::desc("Enable the \"fast\" instruction selector")); 100 101 // Enable or disable an experimental optimization to split GEPs 102 // and run a special GVN pass which does not examine loads, in 103 // an effort to factor out redundancy implicit in complex GEPs. 104 static cl::opt<bool> EnableSplitGEPGVN("split-gep-gvn", cl::Hidden, 105 cl::desc("Split GEPs and run no-load GVN")); 106 107 LLVMTargetMachine::LLVMTargetMachine(const Target &T, 108 const std::string &Triple) 109 : TargetMachine(T), TargetTriple(Triple) { 110 AsmInfo = T.createAsmInfo(TargetTriple); 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? 115 void LLVMTargetMachine::setCodeModelForJIT() { 116 setCodeModel(CodeModel::Small); 117 } 118 119 // Set the default code model for static compilation for a generic target. 120 void LLVMTargetMachine::setCodeModelForStatic() { 121 setCodeModel(CodeModel::Small); 122 } 123 124 bool 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 const MCAsmInfo &MAI = *getMCAsmInfo(); 136 OwningPtr<MCStreamer> AsmStreamer; 137 138 switch (FileType) { 139 default: return true; 140 case CGFT_AssemblyFile: { 141 MCInstPrinter *InstPrinter = 142 getTarget().createMCInstPrinter(MAI.getAssemblerDialect(), MAI); 143 144 // Create a code emitter if asked to show the encoding. 145 MCCodeEmitter *MCE = 0; 146 TargetAsmBackend *TAB = 0; 147 if (ShowMCEncoding) { 148 MCE = getTarget().createCodeEmitter(*this, *Context); 149 TAB = getTarget().createAsmBackend(TargetTriple); 150 } 151 152 MCStreamer *S = getTarget().createAsmStreamer(*Context, Out, 153 getVerboseAsm(), 154 hasMCUseLoc(), 155 InstPrinter, 156 MCE, TAB, 157 ShowMCInst); 158 AsmStreamer.reset(S); 159 break; 160 } 161 case CGFT_ObjectFile: { 162 // Create the code emitter for the target if it exists. If not, .o file 163 // emission fails. 164 MCCodeEmitter *MCE = getTarget().createCodeEmitter(*this, *Context); 165 TargetAsmBackend *TAB = getTarget().createAsmBackend(TargetTriple); 166 if (MCE == 0 || TAB == 0) 167 return true; 168 169 AsmStreamer.reset(getTarget().createObjectStreamer(TargetTriple, *Context, 170 *TAB, Out, MCE, 171 hasMCRelaxAll())); 172 AsmStreamer.get()->InitSections(); 173 break; 174 } 175 case CGFT_Null: 176 // The Null output is intended for use for performance analysis and testing, 177 // not real users. 178 AsmStreamer.reset(createNullStreamer(*Context)); 179 break; 180 } 181 182 if (EnableMCLogging) 183 AsmStreamer.reset(createLoggingStreamer(AsmStreamer.take(), errs())); 184 185 // Create the AsmPrinter, which takes ownership of AsmStreamer if successful. 186 FunctionPass *Printer = getTarget().createAsmPrinter(*this, *AsmStreamer); 187 if (Printer == 0) 188 return true; 189 190 // If successful, createAsmPrinter took ownership of AsmStreamer. 191 AsmStreamer.take(); 192 193 PM.add(Printer); 194 195 // Make sure the code model is set. 196 setCodeModelForStatic(); 197 PM.add(createGCInfoDeleter()); 198 return false; 199 } 200 201 /// addPassesToEmitMachineCode - Add passes to the specified pass manager to 202 /// get machine code emitted. This uses a JITCodeEmitter object to handle 203 /// actually outputting the machine code and resolving things like the address 204 /// of functions. This method should returns true if machine code emission is 205 /// not supported. 206 /// 207 bool LLVMTargetMachine::addPassesToEmitMachineCode(PassManagerBase &PM, 208 JITCodeEmitter &JCE, 209 CodeGenOpt::Level OptLevel, 210 bool DisableVerify) { 211 // Make sure the code model is set. 212 setCodeModelForJIT(); 213 214 // Add common CodeGen passes. 215 MCContext *Ctx = 0; 216 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 217 return true; 218 219 addCodeEmitter(PM, OptLevel, JCE); 220 PM.add(createGCInfoDeleter()); 221 222 return false; // success! 223 } 224 225 /// addPassesToEmitMC - Add passes to the specified pass manager to get 226 /// machine code emitted with the MCJIT. This method returns true if machine 227 /// code is not supported. It fills the MCContext Ctx pointer which can be 228 /// used to build custom MCStreamer. 229 /// 230 bool LLVMTargetMachine::addPassesToEmitMC(PassManagerBase &PM, 231 MCContext *&Ctx, 232 CodeGenOpt::Level OptLevel, 233 bool DisableVerify) { 234 // Add common CodeGen passes. 235 if (addCommonCodeGenPasses(PM, OptLevel, DisableVerify, Ctx)) 236 return true; 237 // Make sure the code model is set. 238 setCodeModelForJIT(); 239 240 return false; // success! 241 } 242 243 static void printNoVerify(PassManagerBase &PM, const char *Banner) { 244 if (PrintMachineCode) 245 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 246 } 247 248 static void printAndVerify(PassManagerBase &PM, 249 const char *Banner) { 250 if (PrintMachineCode) 251 PM.add(createMachineFunctionPrinterPass(dbgs(), Banner)); 252 253 if (VerifyMachineCode) 254 PM.add(createMachineVerifierPass(Banner)); 255 } 256 257 /// addCommonCodeGenPasses - Add standard LLVM codegen passes used for both 258 /// emitting to assembly files or machine code output. 259 /// 260 bool LLVMTargetMachine::addCommonCodeGenPasses(PassManagerBase &PM, 261 CodeGenOpt::Level OptLevel, 262 bool DisableVerify, 263 MCContext *&OutContext) { 264 // Standard LLVM-Level Passes. 265 266 // Basic AliasAnalysis support. 267 createStandardAliasAnalysisPasses(&PM); 268 269 // Before running any passes, run the verifier to determine if the input 270 // coming from the front-end and/or optimizer is valid. 271 if (!DisableVerify) 272 PM.add(createVerifierPass()); 273 274 // Optionally, tun split-GEPs and no-load GVN. 275 if (EnableSplitGEPGVN) { 276 PM.add(createGEPSplitterPass()); 277 PM.add(createGVNPass(/*NoLoads=*/true)); 278 } 279 280 // Run loop strength reduction before anything else. 281 if (OptLevel != CodeGenOpt::None && !DisableLSR) { 282 PM.add(createLoopStrengthReducePass(getTargetLowering())); 283 if (PrintLSR) 284 PM.add(createPrintFunctionPass("\n\n*** Code after LSR ***\n", &dbgs())); 285 } 286 287 PM.add(createGCLoweringPass()); 288 289 // Make sure that no unreachable blocks are instruction selected. 290 PM.add(createUnreachableBlockEliminationPass()); 291 292 // Turn exception handling constructs into something the code generators can 293 // handle. 294 switch (getMCAsmInfo()->getExceptionHandlingType()) { 295 case ExceptionHandling::SjLj: 296 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 297 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 298 // catch info can get misplaced when a selector ends up more than one block 299 // removed from the parent invoke(s). This could happen when a landing 300 // pad is shared by multiple invokes and is also a target of a normal 301 // edge from elsewhere. 302 PM.add(createSjLjEHPass(getTargetLowering())); 303 // FALLTHROUGH 304 case ExceptionHandling::Dwarf: 305 PM.add(createDwarfEHPass(this)); 306 break; 307 case ExceptionHandling::None: 308 PM.add(createLowerInvokePass(getTargetLowering())); 309 310 // The lower invoke pass may create unreachable code. Remove it. 311 PM.add(createUnreachableBlockEliminationPass()); 312 break; 313 } 314 315 if (OptLevel != CodeGenOpt::None && !DisableCGP) 316 PM.add(createCodeGenPreparePass(getTargetLowering())); 317 318 PM.add(createStackProtectorPass(getTargetLowering())); 319 320 addPreISel(PM, OptLevel); 321 322 if (PrintISelInput) 323 PM.add(createPrintFunctionPass("\n\n" 324 "*** Final LLVM Code input to ISel ***\n", 325 &dbgs())); 326 327 // All passes which modify the LLVM IR are now complete; run the verifier 328 // to ensure that the IR is valid. 329 if (!DisableVerify) 330 PM.add(createVerifierPass()); 331 332 // Standard Lower-Level Passes. 333 334 // Install a MachineModuleInfo class, which is an immutable pass that holds 335 // all the per-module stuff we're generating, including MCContext. 336 TargetAsmInfo *TAI = new TargetAsmInfo(*this); 337 MachineModuleInfo *MMI = new MachineModuleInfo(*getMCAsmInfo(), TAI); 338 PM.add(MMI); 339 OutContext = &MMI->getContext(); // Return the MCContext specifically by-ref. 340 341 // Set up a MachineFunction for the rest of CodeGen to work on. 342 PM.add(new MachineFunctionAnalysis(*this, OptLevel)); 343 344 // Enable FastISel with -fast, but allow that to be overridden. 345 if (EnableFastISelOption == cl::BOU_TRUE || 346 (OptLevel == CodeGenOpt::None && EnableFastISelOption != cl::BOU_FALSE)) 347 EnableFastISel = true; 348 349 // Ask the target for an isel. 350 if (addInstSelector(PM, OptLevel)) 351 return true; 352 353 // Print the instruction selected machine code... 354 printAndVerify(PM, "After Instruction Selection"); 355 356 // Expand pseudo-instructions emitted by ISel. 357 PM.add(createExpandISelPseudosPass()); 358 359 // Optimize PHIs before DCE: removing dead PHI cycles may make more 360 // instructions dead. 361 if (OptLevel != CodeGenOpt::None) 362 PM.add(createOptimizePHIsPass()); 363 364 // If the target requests it, assign local variables to stack slots relative 365 // to one another and simplify frame index references where possible. 366 PM.add(createLocalStackSlotAllocationPass()); 367 368 if (OptLevel != CodeGenOpt::None) { 369 // With optimization, dead code should already be eliminated. However 370 // there is one known exception: lowered code for arguments that are only 371 // used by tail calls, where the tail calls reuse the incoming stack 372 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 373 PM.add(createDeadMachineInstructionElimPass()); 374 printAndVerify(PM, "After codegen DCE pass"); 375 376 if (!DisableMachineLICM) 377 PM.add(createMachineLICMPass()); 378 PM.add(createMachineCSEPass()); 379 if (!DisableMachineSink) 380 PM.add(createMachineSinkingPass()); 381 printAndVerify(PM, "After Machine LICM, CSE and Sinking passes"); 382 383 PM.add(createPeepholeOptimizerPass()); 384 printAndVerify(PM, "After codegen peephole optimization pass"); 385 } 386 387 // Pre-ra tail duplication. 388 if (OptLevel != CodeGenOpt::None && !DisableEarlyTailDup) { 389 PM.add(createTailDuplicatePass(true)); 390 printAndVerify(PM, "After Pre-RegAlloc TailDuplicate"); 391 } 392 393 // Run pre-ra passes. 394 if (addPreRegAlloc(PM, OptLevel)) 395 printAndVerify(PM, "After PreRegAlloc passes"); 396 397 // Perform register allocation. 398 PM.add(createRegisterAllocator(OptLevel)); 399 printAndVerify(PM, "After Register Allocation"); 400 401 // Perform stack slot coloring and post-ra machine LICM. 402 if (OptLevel != CodeGenOpt::None) { 403 // FIXME: Re-enable coloring with register when it's capable of adding 404 // kill markers. 405 if (!DisableSSC) 406 PM.add(createStackSlotColoringPass(false)); 407 408 // Run post-ra machine LICM to hoist reloads / remats. 409 if (!DisablePostRAMachineLICM) 410 PM.add(createMachineLICMPass(false)); 411 412 printAndVerify(PM, "After StackSlotColoring and postra Machine LICM"); 413 } 414 415 // Run post-ra passes. 416 if (addPostRegAlloc(PM, OptLevel)) 417 printAndVerify(PM, "After PostRegAlloc passes"); 418 419 PM.add(createLowerSubregsPass()); 420 printAndVerify(PM, "After LowerSubregs"); 421 422 // Insert prolog/epilog code. Eliminate abstract frame index references... 423 PM.add(createPrologEpilogCodeInserter()); 424 printAndVerify(PM, "After PrologEpilogCodeInserter"); 425 426 // Run pre-sched2 passes. 427 if (addPreSched2(PM, OptLevel)) 428 printAndVerify(PM, "After PreSched2 passes"); 429 430 // Second pass scheduler. 431 if (OptLevel != CodeGenOpt::None && !DisablePostRA) { 432 PM.add(createPostRAScheduler(OptLevel)); 433 printAndVerify(PM, "After PostRAScheduler"); 434 } 435 436 // Branch folding must be run after regalloc and prolog/epilog insertion. 437 if (OptLevel != CodeGenOpt::None && !DisableBranchFold) { 438 PM.add(createBranchFoldingPass(getEnableTailMergeDefault())); 439 printNoVerify(PM, "After BranchFolding"); 440 } 441 442 // Tail duplication. 443 if (OptLevel != CodeGenOpt::None && !DisableTailDuplicate) { 444 PM.add(createTailDuplicatePass(false)); 445 printNoVerify(PM, "After TailDuplicate"); 446 } 447 448 PM.add(createGCMachineCodeAnalysisPass()); 449 450 if (PrintGCInfo) 451 PM.add(createGCInfoPrinter(dbgs())); 452 453 if (OptLevel != CodeGenOpt::None && !DisableCodePlace) { 454 PM.add(createCodePlacementOptPass()); 455 printNoVerify(PM, "After CodePlacementOpt"); 456 } 457 458 if (addPreEmitPass(PM, OptLevel)) 459 printNoVerify(PM, "After PreEmit passes"); 460 461 return false; 462 } 463