1 //===-- TargetPassConfig.cpp - Target independent code generation passes --===// 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 defines interfaces to access the target independent code 11 // generation passes provided by the LLVM backend. 12 // 13 //===---------------------------------------------------------------------===// 14 15 #include "llvm/CodeGen/TargetPassConfig.h" 16 17 #include "llvm/Analysis/BasicAliasAnalysis.h" 18 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 20 #include "llvm/Analysis/CallGraphSCCPass.h" 21 #include "llvm/Analysis/Passes.h" 22 #include "llvm/Analysis/ScopedNoAliasAA.h" 23 #include "llvm/Analysis/TargetTransformInfo.h" 24 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 25 #include "llvm/CodeGen/MachineFunctionPass.h" 26 #include "llvm/CodeGen/RegAllocRegistry.h" 27 #include "llvm/CodeGen/RegisterUsageInfo.h" 28 #include "llvm/IR/IRPrintingPasses.h" 29 #include "llvm/IR/LegacyPassManager.h" 30 #include "llvm/IR/Verifier.h" 31 #include "llvm/MC/MCAsmInfo.h" 32 #include "llvm/Support/Debug.h" 33 #include "llvm/Support/ErrorHandling.h" 34 #include "llvm/Support/raw_ostream.h" 35 #include "llvm/Target/TargetMachine.h" 36 #include "llvm/Transforms/Instrumentation.h" 37 #include "llvm/Transforms/Scalar.h" 38 #include "llvm/Transforms/Utils/SymbolRewriter.h" 39 40 using namespace llvm; 41 42 static cl::opt<bool> DisablePostRASched("disable-post-ra", cl::Hidden, 43 cl::desc("Disable Post Regalloc Scheduler")); 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> DisableBlockPlacement("disable-block-placement", 51 cl::Hidden, cl::desc("Disable probability-driven block placement")); 52 static cl::opt<bool> EnableBlockPlacementStats("enable-block-placement-stats", 53 cl::Hidden, cl::desc("Collect probability-driven block placement stats")); 54 static cl::opt<bool> DisableSSC("disable-ssc", cl::Hidden, 55 cl::desc("Disable Stack Slot Coloring")); 56 static cl::opt<bool> DisableMachineDCE("disable-machine-dce", cl::Hidden, 57 cl::desc("Disable Machine Dead Code Elimination")); 58 static cl::opt<bool> DisableEarlyIfConversion("disable-early-ifcvt", cl::Hidden, 59 cl::desc("Disable Early If-conversion")); 60 static cl::opt<bool> DisableMachineLICM("disable-machine-licm", cl::Hidden, 61 cl::desc("Disable Machine LICM")); 62 static cl::opt<bool> DisableMachineCSE("disable-machine-cse", cl::Hidden, 63 cl::desc("Disable Machine Common Subexpression Elimination")); 64 static cl::opt<cl::boolOrDefault> OptimizeRegAlloc( 65 "optimize-regalloc", cl::Hidden, 66 cl::desc("Enable optimized register allocation compilation path.")); 67 static cl::opt<bool> DisablePostRAMachineLICM("disable-postra-machine-licm", 68 cl::Hidden, 69 cl::desc("Disable Machine LICM")); 70 static cl::opt<bool> DisableMachineSink("disable-machine-sink", cl::Hidden, 71 cl::desc("Disable Machine Sinking")); 72 static cl::opt<bool> DisableLSR("disable-lsr", cl::Hidden, 73 cl::desc("Disable Loop Strength Reduction Pass")); 74 static cl::opt<bool> DisableConstantHoisting("disable-constant-hoisting", 75 cl::Hidden, cl::desc("Disable ConstantHoisting")); 76 static cl::opt<bool> DisableCGP("disable-cgp", cl::Hidden, 77 cl::desc("Disable Codegen Prepare")); 78 static cl::opt<bool> DisableCopyProp("disable-copyprop", cl::Hidden, 79 cl::desc("Disable Copy Propagation pass")); 80 static cl::opt<bool> DisablePartialLibcallInlining("disable-partial-libcall-inlining", 81 cl::Hidden, cl::desc("Disable Partial Libcall Inlining")); 82 static cl::opt<bool> EnableImplicitNullChecks( 83 "enable-implicit-null-checks", 84 cl::desc("Fold null checks into faulting memory operations"), 85 cl::init(false)); 86 static cl::opt<bool> PrintLSR("print-lsr-output", cl::Hidden, 87 cl::desc("Print LLVM IR produced by the loop-reduce pass")); 88 static cl::opt<bool> PrintISelInput("print-isel-input", cl::Hidden, 89 cl::desc("Print LLVM IR input to isel pass")); 90 static cl::opt<bool> PrintGCInfo("print-gc", cl::Hidden, 91 cl::desc("Dump garbage collector data")); 92 static cl::opt<bool> VerifyMachineCode("verify-machineinstrs", cl::Hidden, 93 cl::desc("Verify generated machine code"), 94 cl::init(false), 95 cl::ZeroOrMore); 96 static cl::opt<bool> EnableMachineOutliner("enable-machine-outliner", 97 cl::Hidden, 98 cl::desc("Enable machine outliner")); 99 // Enable or disable FastISel. Both options are needed, because 100 // FastISel is enabled by default with -fast, and we wish to be 101 // able to enable or disable fast-isel independently from -O0. 102 static cl::opt<cl::boolOrDefault> 103 EnableFastISelOption("fast-isel", cl::Hidden, 104 cl::desc("Enable the \"fast\" instruction selector")); 105 106 static cl::opt<cl::boolOrDefault> 107 EnableGlobalISel("global-isel", cl::Hidden, 108 cl::desc("Enable the \"global\" instruction selector")); 109 110 static cl::opt<std::string> 111 PrintMachineInstrs("print-machineinstrs", cl::ValueOptional, 112 cl::desc("Print machine instrs"), 113 cl::value_desc("pass-name"), cl::init("option-unspecified")); 114 115 static cl::opt<int> EnableGlobalISelAbort( 116 "global-isel-abort", cl::Hidden, 117 cl::desc("Enable abort calls when \"global\" instruction selection " 118 "fails to lower/select an instruction: 0 disable the abort, " 119 "1 enable the abort, and " 120 "2 disable the abort but emit a diagnostic on failure"), 121 cl::init(1)); 122 123 // Temporary option to allow experimenting with MachineScheduler as a post-RA 124 // scheduler. Targets can "properly" enable this with 125 // substitutePass(&PostRASchedulerID, &PostMachineSchedulerID). 126 // Targets can return true in targetSchedulesPostRAScheduling() and 127 // insert a PostRA scheduling pass wherever it wants. 128 cl::opt<bool> MISchedPostRA("misched-postra", cl::Hidden, 129 cl::desc("Run MachineScheduler post regalloc (independent of preRA sched)")); 130 131 // Experimental option to run live interval analysis early. 132 static cl::opt<bool> EarlyLiveIntervals("early-live-intervals", cl::Hidden, 133 cl::desc("Run live interval analysis earlier in the pipeline")); 134 135 // Experimental option to use CFL-AA in codegen 136 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 137 static cl::opt<CFLAAType> UseCFLAA( 138 "use-cfl-aa-in-codegen", cl::init(CFLAAType::None), cl::Hidden, 139 cl::desc("Enable the new, experimental CFL alias analysis in CodeGen"), 140 cl::values(clEnumValN(CFLAAType::None, "none", "Disable CFL-AA"), 141 clEnumValN(CFLAAType::Steensgaard, "steens", 142 "Enable unification-based CFL-AA"), 143 clEnumValN(CFLAAType::Andersen, "anders", 144 "Enable inclusion-based CFL-AA"), 145 clEnumValN(CFLAAType::Both, "both", 146 "Enable both variants of CFL-AA"))); 147 148 /// Allow standard passes to be disabled by command line options. This supports 149 /// simple binary flags that either suppress the pass or do nothing. 150 /// i.e. -disable-mypass=false has no effect. 151 /// These should be converted to boolOrDefault in order to use applyOverride. 152 static IdentifyingPassPtr applyDisable(IdentifyingPassPtr PassID, 153 bool Override) { 154 if (Override) 155 return IdentifyingPassPtr(); 156 return PassID; 157 } 158 159 /// Allow standard passes to be disabled by the command line, regardless of who 160 /// is adding the pass. 161 /// 162 /// StandardID is the pass identified in the standard pass pipeline and provided 163 /// to addPass(). It may be a target-specific ID in the case that the target 164 /// directly adds its own pass, but in that case we harmlessly fall through. 165 /// 166 /// TargetID is the pass that the target has configured to override StandardID. 167 /// 168 /// StandardID may be a pseudo ID. In that case TargetID is the name of the real 169 /// pass to run. This allows multiple options to control a single pass depending 170 /// on where in the pipeline that pass is added. 171 static IdentifyingPassPtr overridePass(AnalysisID StandardID, 172 IdentifyingPassPtr TargetID) { 173 if (StandardID == &PostRASchedulerID) 174 return applyDisable(TargetID, DisablePostRASched); 175 176 if (StandardID == &BranchFolderPassID) 177 return applyDisable(TargetID, DisableBranchFold); 178 179 if (StandardID == &TailDuplicateID) 180 return applyDisable(TargetID, DisableTailDuplicate); 181 182 if (StandardID == &TargetPassConfig::EarlyTailDuplicateID) 183 return applyDisable(TargetID, DisableEarlyTailDup); 184 185 if (StandardID == &MachineBlockPlacementID) 186 return applyDisable(TargetID, DisableBlockPlacement); 187 188 if (StandardID == &StackSlotColoringID) 189 return applyDisable(TargetID, DisableSSC); 190 191 if (StandardID == &DeadMachineInstructionElimID) 192 return applyDisable(TargetID, DisableMachineDCE); 193 194 if (StandardID == &EarlyIfConverterID) 195 return applyDisable(TargetID, DisableEarlyIfConversion); 196 197 if (StandardID == &MachineLICMID) 198 return applyDisable(TargetID, DisableMachineLICM); 199 200 if (StandardID == &MachineCSEID) 201 return applyDisable(TargetID, DisableMachineCSE); 202 203 if (StandardID == &TargetPassConfig::PostRAMachineLICMID) 204 return applyDisable(TargetID, DisablePostRAMachineLICM); 205 206 if (StandardID == &MachineSinkingID) 207 return applyDisable(TargetID, DisableMachineSink); 208 209 if (StandardID == &MachineCopyPropagationID) 210 return applyDisable(TargetID, DisableCopyProp); 211 212 return TargetID; 213 } 214 215 //===---------------------------------------------------------------------===// 216 /// TargetPassConfig 217 //===---------------------------------------------------------------------===// 218 219 INITIALIZE_PASS(TargetPassConfig, "targetpassconfig", 220 "Target Pass Configuration", false, false) 221 char TargetPassConfig::ID = 0; 222 223 // Pseudo Pass IDs. 224 char TargetPassConfig::EarlyTailDuplicateID = 0; 225 char TargetPassConfig::PostRAMachineLICMID = 0; 226 227 namespace { 228 struct InsertedPass { 229 AnalysisID TargetPassID; 230 IdentifyingPassPtr InsertedPassID; 231 bool VerifyAfter; 232 bool PrintAfter; 233 234 InsertedPass(AnalysisID TargetPassID, IdentifyingPassPtr InsertedPassID, 235 bool VerifyAfter, bool PrintAfter) 236 : TargetPassID(TargetPassID), InsertedPassID(InsertedPassID), 237 VerifyAfter(VerifyAfter), PrintAfter(PrintAfter) {} 238 239 Pass *getInsertedPass() const { 240 assert(InsertedPassID.isValid() && "Illegal Pass ID!"); 241 if (InsertedPassID.isInstance()) 242 return InsertedPassID.getInstance(); 243 Pass *NP = Pass::createPass(InsertedPassID.getID()); 244 assert(NP && "Pass ID not registered"); 245 return NP; 246 } 247 }; 248 } 249 250 namespace llvm { 251 class PassConfigImpl { 252 public: 253 // List of passes explicitly substituted by this target. Normally this is 254 // empty, but it is a convenient way to suppress or replace specific passes 255 // that are part of a standard pass pipeline without overridding the entire 256 // pipeline. This mechanism allows target options to inherit a standard pass's 257 // user interface. For example, a target may disable a standard pass by 258 // default by substituting a pass ID of zero, and the user may still enable 259 // that standard pass with an explicit command line option. 260 DenseMap<AnalysisID,IdentifyingPassPtr> TargetPasses; 261 262 /// Store the pairs of <AnalysisID, AnalysisID> of which the second pass 263 /// is inserted after each instance of the first one. 264 SmallVector<InsertedPass, 4> InsertedPasses; 265 }; 266 } // namespace llvm 267 268 // Out of line virtual method. 269 TargetPassConfig::~TargetPassConfig() { 270 delete Impl; 271 } 272 273 // Out of line constructor provides default values for pass options and 274 // registers all common codegen passes. 275 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm) 276 : ImmutablePass(ID), PM(&pm), Started(true), Stopped(false), 277 AddingMachinePasses(false), TM(&TM), Impl(nullptr), Initialized(false), 278 DisableVerify(false), EnableTailMerge(true), 279 RequireCodeGenSCCOrder(false) { 280 281 Impl = new PassConfigImpl(); 282 283 // Register all target independent codegen passes to activate their PassIDs, 284 // including this pass itself. 285 initializeCodeGen(*PassRegistry::getPassRegistry()); 286 287 // Also register alias analysis passes required by codegen passes. 288 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 289 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 290 291 // Substitute Pseudo Pass IDs for real ones. 292 substitutePass(&EarlyTailDuplicateID, &TailDuplicateID); 293 substitutePass(&PostRAMachineLICMID, &MachineLICMID); 294 295 if (StringRef(PrintMachineInstrs.getValue()).equals("")) 296 TM.Options.PrintMachineCode = true; 297 298 if (TM.Options.EnableIPRA) 299 setRequiresCodeGenSCCOrder(); 300 } 301 302 CodeGenOpt::Level TargetPassConfig::getOptLevel() const { 303 return TM->getOptLevel(); 304 } 305 306 /// Insert InsertedPassID pass after TargetPassID. 307 void TargetPassConfig::insertPass(AnalysisID TargetPassID, 308 IdentifyingPassPtr InsertedPassID, 309 bool VerifyAfter, bool PrintAfter) { 310 assert(((!InsertedPassID.isInstance() && 311 TargetPassID != InsertedPassID.getID()) || 312 (InsertedPassID.isInstance() && 313 TargetPassID != InsertedPassID.getInstance()->getPassID())) && 314 "Insert a pass after itself!"); 315 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID, VerifyAfter, 316 PrintAfter); 317 } 318 319 /// createPassConfig - Create a pass configuration object to be used by 320 /// addPassToEmitX methods for generating a pipeline of CodeGen passes. 321 /// 322 /// Targets may override this to extend TargetPassConfig. 323 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) { 324 return new TargetPassConfig(*this, PM); 325 } 326 327 TargetPassConfig::TargetPassConfig() 328 : ImmutablePass(ID), PM(nullptr) { 329 report_fatal_error("Trying to construct TargetPassConfig without a target " 330 "machine. Scheduling a CodeGen pass without a target " 331 "triple set?"); 332 } 333 334 // Helper to verify the analysis is really immutable. 335 void TargetPassConfig::setOpt(bool &Opt, bool Val) { 336 assert(!Initialized && "PassConfig is immutable"); 337 Opt = Val; 338 } 339 340 void TargetPassConfig::substitutePass(AnalysisID StandardID, 341 IdentifyingPassPtr TargetID) { 342 Impl->TargetPasses[StandardID] = TargetID; 343 } 344 345 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const { 346 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator 347 I = Impl->TargetPasses.find(ID); 348 if (I == Impl->TargetPasses.end()) 349 return ID; 350 return I->second; 351 } 352 353 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const { 354 IdentifyingPassPtr TargetID = getPassSubstitution(ID); 355 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID); 356 return !FinalPtr.isValid() || FinalPtr.isInstance() || 357 FinalPtr.getID() != ID; 358 } 359 360 /// Add a pass to the PassManager if that pass is supposed to be run. If the 361 /// Started/Stopped flags indicate either that the compilation should start at 362 /// a later pass or that it should stop after an earlier pass, then do not add 363 /// the pass. Finally, compare the current pass against the StartAfter 364 /// and StopAfter options and change the Started/Stopped flags accordingly. 365 void TargetPassConfig::addPass(Pass *P, bool verifyAfter, bool printAfter) { 366 assert(!Initialized && "PassConfig is immutable"); 367 368 // Cache the Pass ID here in case the pass manager finds this pass is 369 // redundant with ones already scheduled / available, and deletes it. 370 // Fundamentally, once we add the pass to the manager, we no longer own it 371 // and shouldn't reference it. 372 AnalysisID PassID = P->getPassID(); 373 374 if (StartBefore == PassID) 375 Started = true; 376 if (StopBefore == PassID) 377 Stopped = true; 378 if (Started && !Stopped) { 379 std::string Banner; 380 // Construct banner message before PM->add() as that may delete the pass. 381 if (AddingMachinePasses && (printAfter || verifyAfter)) 382 Banner = std::string("After ") + std::string(P->getPassName()); 383 PM->add(P); 384 if (AddingMachinePasses) { 385 if (printAfter) 386 addPrintPass(Banner); 387 if (verifyAfter) 388 addVerifyPass(Banner); 389 } 390 391 // Add the passes after the pass P if there is any. 392 for (auto IP : Impl->InsertedPasses) { 393 if (IP.TargetPassID == PassID) 394 addPass(IP.getInsertedPass(), IP.VerifyAfter, IP.PrintAfter); 395 } 396 } else { 397 delete P; 398 } 399 if (StopAfter == PassID) 400 Stopped = true; 401 if (StartAfter == PassID) 402 Started = true; 403 if (Stopped && !Started) 404 report_fatal_error("Cannot stop compilation after pass that is not run"); 405 } 406 407 /// Add a CodeGen pass at this point in the pipeline after checking for target 408 /// and command line overrides. 409 /// 410 /// addPass cannot return a pointer to the pass instance because is internal the 411 /// PassManager and the instance we create here may already be freed. 412 AnalysisID TargetPassConfig::addPass(AnalysisID PassID, bool verifyAfter, 413 bool printAfter) { 414 IdentifyingPassPtr TargetID = getPassSubstitution(PassID); 415 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID); 416 if (!FinalPtr.isValid()) 417 return nullptr; 418 419 Pass *P; 420 if (FinalPtr.isInstance()) 421 P = FinalPtr.getInstance(); 422 else { 423 P = Pass::createPass(FinalPtr.getID()); 424 if (!P) 425 llvm_unreachable("Pass ID not registered"); 426 } 427 AnalysisID FinalID = P->getPassID(); 428 addPass(P, verifyAfter, printAfter); // Ends the lifetime of P. 429 430 return FinalID; 431 } 432 433 void TargetPassConfig::printAndVerify(const std::string &Banner) { 434 addPrintPass(Banner); 435 addVerifyPass(Banner); 436 } 437 438 void TargetPassConfig::addPrintPass(const std::string &Banner) { 439 if (TM->shouldPrintMachineCode()) 440 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner)); 441 } 442 443 void TargetPassConfig::addVerifyPass(const std::string &Banner) { 444 bool Verify = VerifyMachineCode; 445 #ifdef EXPENSIVE_CHECKS 446 if (VerifyMachineCode == cl::BOU_UNSET) 447 Verify = TM->isMachineVerifierClean(); 448 #endif 449 if (Verify) 450 PM->add(createMachineVerifierPass(Banner)); 451 } 452 453 /// Add common target configurable passes that perform LLVM IR to IR transforms 454 /// following machine independent optimization. 455 void TargetPassConfig::addIRPasses() { 456 switch (UseCFLAA) { 457 case CFLAAType::Steensgaard: 458 addPass(createCFLSteensAAWrapperPass()); 459 break; 460 case CFLAAType::Andersen: 461 addPass(createCFLAndersAAWrapperPass()); 462 break; 463 case CFLAAType::Both: 464 addPass(createCFLAndersAAWrapperPass()); 465 addPass(createCFLSteensAAWrapperPass()); 466 break; 467 default: 468 break; 469 } 470 471 // Basic AliasAnalysis support. 472 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 473 // BasicAliasAnalysis wins if they disagree. This is intended to help 474 // support "obvious" type-punning idioms. 475 addPass(createTypeBasedAAWrapperPass()); 476 addPass(createScopedNoAliasAAWrapperPass()); 477 addPass(createBasicAAWrapperPass()); 478 479 // Before running any passes, run the verifier to determine if the input 480 // coming from the front-end and/or optimizer is valid. 481 if (!DisableVerify) 482 addPass(createVerifierPass()); 483 484 // Run loop strength reduction before anything else. 485 if (getOptLevel() != CodeGenOpt::None && !DisableLSR) { 486 addPass(createLoopStrengthReducePass()); 487 if (PrintLSR) 488 addPass(createPrintFunctionPass(dbgs(), "\n\n*** Code after LSR ***\n")); 489 } 490 491 // Run GC lowering passes for builtin collectors 492 // TODO: add a pass insertion point here 493 addPass(createGCLoweringPass()); 494 addPass(createShadowStackGCLoweringPass()); 495 496 // Make sure that no unreachable blocks are instruction selected. 497 addPass(createUnreachableBlockEliminationPass()); 498 499 // Prepare expensive constants for SelectionDAG. 500 if (getOptLevel() != CodeGenOpt::None && !DisableConstantHoisting) 501 addPass(createConstantHoistingPass()); 502 503 if (getOptLevel() != CodeGenOpt::None && !DisablePartialLibcallInlining) 504 addPass(createPartiallyInlineLibCallsPass()); 505 506 // Insert calls to mcount-like functions. 507 addPass(createCountingFunctionInserterPass()); 508 509 // Add scalarization of target's unsupported masked memory intrinsics pass. 510 // the unsupported intrinsic will be replaced with a chain of basic blocks, 511 // that stores/loads element one-by-one if the appropriate mask bit is set. 512 addPass(createScalarizeMaskedMemIntrinPass()); 513 514 // Expand reduction intrinsics into shuffle sequences if the target wants to. 515 addPass(createExpandReductionsPass()); 516 } 517 518 /// Turn exception handling constructs into something the code generators can 519 /// handle. 520 void TargetPassConfig::addPassesToHandleExceptions() { 521 const MCAsmInfo *MCAI = TM->getMCAsmInfo(); 522 assert(MCAI && "No MCAsmInfo"); 523 switch (MCAI->getExceptionHandlingType()) { 524 case ExceptionHandling::SjLj: 525 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 526 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 527 // catch info can get misplaced when a selector ends up more than one block 528 // removed from the parent invoke(s). This could happen when a landing 529 // pad is shared by multiple invokes and is also a target of a normal 530 // edge from elsewhere. 531 addPass(createSjLjEHPreparePass()); 532 LLVM_FALLTHROUGH; 533 case ExceptionHandling::DwarfCFI: 534 case ExceptionHandling::ARM: 535 addPass(createDwarfEHPass()); 536 break; 537 case ExceptionHandling::WinEH: 538 // We support using both GCC-style and MSVC-style exceptions on Windows, so 539 // add both preparation passes. Each pass will only actually run if it 540 // recognizes the personality function. 541 addPass(createWinEHPass()); 542 addPass(createDwarfEHPass()); 543 break; 544 case ExceptionHandling::None: 545 addPass(createLowerInvokePass()); 546 547 // The lower invoke pass may create unreachable code. Remove it. 548 addPass(createUnreachableBlockEliminationPass()); 549 break; 550 } 551 } 552 553 /// Add pass to prepare the LLVM IR for code generation. This should be done 554 /// before exception handling preparation passes. 555 void TargetPassConfig::addCodeGenPrepare() { 556 if (getOptLevel() != CodeGenOpt::None && !DisableCGP) 557 addPass(createCodeGenPreparePass()); 558 addPass(createRewriteSymbolsPass()); 559 } 560 561 /// Add common passes that perform LLVM IR to IR transforms in preparation for 562 /// instruction selection. 563 void TargetPassConfig::addISelPrepare() { 564 addPreISel(); 565 566 // Force codegen to run according to the callgraph. 567 if (requiresCodeGenSCCOrder()) 568 addPass(new DummyCGSCCPass); 569 570 // Add both the safe stack and the stack protection passes: each of them will 571 // only protect functions that have corresponding attributes. 572 addPass(createSafeStackPass()); 573 addPass(createStackProtectorPass()); 574 575 if (PrintISelInput) 576 addPass(createPrintFunctionPass( 577 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n")); 578 579 // All passes which modify the LLVM IR are now complete; run the verifier 580 // to ensure that the IR is valid. 581 if (!DisableVerify) 582 addPass(createVerifierPass()); 583 } 584 585 bool TargetPassConfig::addCoreISelPasses() { 586 // Enable FastISel with -fast, but allow that to be overridden. 587 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 588 if (EnableFastISelOption == cl::BOU_TRUE || 589 (TM->getOptLevel() == CodeGenOpt::None && TM->getO0WantsFastISel())) 590 TM->setFastISel(true); 591 592 // Ask the target for an isel. 593 // Enable GlobalISel if the target wants to, but allow that to be overriden. 594 if (EnableGlobalISel == cl::BOU_TRUE || 595 (EnableGlobalISel == cl::BOU_UNSET && isGlobalISelEnabled())) { 596 if (addIRTranslator()) 597 return true; 598 599 addPreLegalizeMachineIR(); 600 601 if (addLegalizeMachineIR()) 602 return true; 603 604 // Before running the register bank selector, ask the target if it 605 // wants to run some passes. 606 addPreRegBankSelect(); 607 608 if (addRegBankSelect()) 609 return true; 610 611 addPreGlobalInstructionSelect(); 612 613 if (addGlobalInstructionSelect()) 614 return true; 615 616 // Pass to reset the MachineFunction if the ISel failed. 617 addPass(createResetMachineFunctionPass( 618 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled())); 619 620 // Provide a fallback path when we do not want to abort on 621 // not-yet-supported input. 622 if (!isGlobalISelAbortEnabled() && addInstSelector()) 623 return true; 624 625 } else if (addInstSelector()) 626 return true; 627 628 return false; 629 } 630 631 bool TargetPassConfig::addISelPasses() { 632 if (TM->Options.EmulatedTLS) 633 addPass(createLowerEmuTLSPass()); 634 635 addPass(createPreISelIntrinsicLoweringPass()); 636 addPass(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 637 addIRPasses(); 638 addCodeGenPrepare(); 639 addPassesToHandleExceptions(); 640 addISelPrepare(); 641 642 return addCoreISelPasses(); 643 } 644 645 /// -regalloc=... command line option. 646 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 647 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false, 648 RegisterPassParser<RegisterRegAlloc> > 649 RegAlloc("regalloc", 650 cl::init(&useDefaultRegisterAllocator), 651 cl::desc("Register allocator to use")); 652 653 /// Add the complete set of target-independent postISel code generator passes. 654 /// 655 /// This can be read as the standard order of major LLVM CodeGen stages. Stages 656 /// with nontrivial configuration or multiple passes are broken out below in 657 /// add%Stage routines. 658 /// 659 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The 660 /// addPre/Post methods with empty header implementations allow injecting 661 /// target-specific fixups just before or after major stages. Additionally, 662 /// targets have the flexibility to change pass order within a stage by 663 /// overriding default implementation of add%Stage routines below. Each 664 /// technique has maintainability tradeoffs because alternate pass orders are 665 /// not well supported. addPre/Post works better if the target pass is easily 666 /// tied to a common pass. But if it has subtle dependencies on multiple passes, 667 /// the target should override the stage instead. 668 /// 669 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection 670 /// before/after any target-independent pass. But it's currently overkill. 671 void TargetPassConfig::addMachinePasses() { 672 AddingMachinePasses = true; 673 674 // Insert a machine instr printer pass after the specified pass. 675 if (!StringRef(PrintMachineInstrs.getValue()).equals("") && 676 !StringRef(PrintMachineInstrs.getValue()).equals("option-unspecified")) { 677 const PassRegistry *PR = PassRegistry::getPassRegistry(); 678 const PassInfo *TPI = PR->getPassInfo(PrintMachineInstrs.getValue()); 679 const PassInfo *IPI = PR->getPassInfo(StringRef("machineinstr-printer")); 680 assert (TPI && IPI && "Pass ID not registered!"); 681 const char *TID = (const char *)(TPI->getTypeInfo()); 682 const char *IID = (const char *)(IPI->getTypeInfo()); 683 insertPass(TID, IID); 684 } 685 686 // Print the instruction selected machine code... 687 printAndVerify("After Instruction Selection"); 688 689 if (TM->Options.EnableIPRA) 690 addPass(createRegUsageInfoPropPass()); 691 692 // Expand pseudo-instructions emitted by ISel. 693 addPass(&ExpandISelPseudosID); 694 695 // Add passes that optimize machine instructions in SSA form. 696 if (getOptLevel() != CodeGenOpt::None) { 697 addMachineSSAOptimization(); 698 } else { 699 // If the target requests it, assign local variables to stack slots relative 700 // to one another and simplify frame index references where possible. 701 addPass(&LocalStackSlotAllocationID, false); 702 } 703 704 // Run pre-ra passes. 705 addPreRegAlloc(); 706 707 // Run register allocation and passes that are tightly coupled with it, 708 // including phi elimination and scheduling. 709 if (getOptimizeRegAlloc()) 710 addOptimizedRegAlloc(createRegAllocPass(true)); 711 else { 712 if (RegAlloc != &useDefaultRegisterAllocator && 713 RegAlloc != &createFastRegisterAllocator) 714 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc."); 715 addFastRegAlloc(createRegAllocPass(false)); 716 } 717 718 // Run post-ra passes. 719 addPostRegAlloc(); 720 721 // Insert prolog/epilog code. Eliminate abstract frame index references... 722 if (getOptLevel() != CodeGenOpt::None) 723 addPass(&ShrinkWrapID); 724 725 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only 726 // do so if it hasn't been disabled, substituted, or overridden. 727 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID)) 728 addPass(createPrologEpilogInserterPass()); 729 730 /// Add passes that optimize machine instructions after register allocation. 731 if (getOptLevel() != CodeGenOpt::None) 732 addMachineLateOptimization(); 733 734 // Expand pseudo instructions before second scheduling pass. 735 addPass(&ExpandPostRAPseudosID); 736 737 // Run pre-sched2 passes. 738 addPreSched2(); 739 740 if (EnableImplicitNullChecks) 741 addPass(&ImplicitNullChecksID); 742 743 // Second pass scheduler. 744 // Let Target optionally insert this pass by itself at some other 745 // point. 746 if (getOptLevel() != CodeGenOpt::None && 747 !TM->targetSchedulesPostRAScheduling()) { 748 if (MISchedPostRA) 749 addPass(&PostMachineSchedulerID); 750 else 751 addPass(&PostRASchedulerID); 752 } 753 754 // GC 755 if (addGCPasses()) { 756 if (PrintGCInfo) 757 addPass(createGCInfoPrinter(dbgs()), false, false); 758 } 759 760 // Basic block placement. 761 if (getOptLevel() != CodeGenOpt::None) 762 addBlockPlacement(); 763 764 addPreEmitPass(); 765 766 if (TM->Options.EnableIPRA) 767 // Collect register usage information and produce a register mask of 768 // clobbered registers, to be used to optimize call sites. 769 addPass(createRegUsageInfoCollector()); 770 771 addPass(&FuncletLayoutID, false); 772 773 addPass(&StackMapLivenessID, false); 774 addPass(&LiveDebugValuesID, false); 775 776 // Insert before XRay Instrumentation. 777 addPass(&FEntryInserterID, false); 778 779 addPass(&XRayInstrumentationID, false); 780 addPass(&PatchableFunctionID, false); 781 782 if (EnableMachineOutliner) 783 PM->add(createMachineOutlinerPass()); 784 785 AddingMachinePasses = false; 786 } 787 788 /// Add passes that optimize machine instructions in SSA form. 789 void TargetPassConfig::addMachineSSAOptimization() { 790 // Pre-ra tail duplication. 791 addPass(&EarlyTailDuplicateID); 792 793 // Optimize PHIs before DCE: removing dead PHI cycles may make more 794 // instructions dead. 795 addPass(&OptimizePHIsID, false); 796 797 // This pass merges large allocas. StackSlotColoring is a different pass 798 // which merges spill slots. 799 addPass(&StackColoringID, false); 800 801 // If the target requests it, assign local variables to stack slots relative 802 // to one another and simplify frame index references where possible. 803 addPass(&LocalStackSlotAllocationID, false); 804 805 // With optimization, dead code should already be eliminated. However 806 // there is one known exception: lowered code for arguments that are only 807 // used by tail calls, where the tail calls reuse the incoming stack 808 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 809 addPass(&DeadMachineInstructionElimID); 810 811 // Allow targets to insert passes that improve instruction level parallelism, 812 // like if-conversion. Such passes will typically need dominator trees and 813 // loop info, just like LICM and CSE below. 814 addILPOpts(); 815 816 addPass(&MachineLICMID, false); 817 addPass(&MachineCSEID, false); 818 819 // Coalesce basic blocks with the same branch condition 820 addPass(&BranchCoalescingID); 821 822 addPass(&MachineSinkingID); 823 824 addPass(&PeepholeOptimizerID); 825 // Clean-up the dead code that may have been generated by peephole 826 // rewriting. 827 addPass(&DeadMachineInstructionElimID); 828 } 829 830 //===---------------------------------------------------------------------===// 831 /// Register Allocation Pass Configuration 832 //===---------------------------------------------------------------------===// 833 834 bool TargetPassConfig::getOptimizeRegAlloc() const { 835 switch (OptimizeRegAlloc) { 836 case cl::BOU_UNSET: return getOptLevel() != CodeGenOpt::None; 837 case cl::BOU_TRUE: return true; 838 case cl::BOU_FALSE: return false; 839 } 840 llvm_unreachable("Invalid optimize-regalloc state"); 841 } 842 843 /// RegisterRegAlloc's global Registry tracks allocator registration. 844 MachinePassRegistry RegisterRegAlloc::Registry; 845 846 /// A dummy default pass factory indicates whether the register allocator is 847 /// overridden on the command line. 848 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag; 849 850 static RegisterRegAlloc 851 defaultRegAlloc("default", 852 "pick register allocator based on -O option", 853 useDefaultRegisterAllocator); 854 855 static void initializeDefaultRegisterAllocatorOnce() { 856 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 857 858 if (!Ctor) { 859 Ctor = RegAlloc; 860 RegisterRegAlloc::setDefault(RegAlloc); 861 } 862 } 863 864 /// Instantiate the default register allocator pass for this target for either 865 /// the optimized or unoptimized allocation path. This will be added to the pass 866 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc 867 /// in the optimized case. 868 /// 869 /// A target that uses the standard regalloc pass order for fast or optimized 870 /// allocation may still override this for per-target regalloc 871 /// selection. But -regalloc=... always takes precedence. 872 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) { 873 if (Optimized) 874 return createGreedyRegisterAllocator(); 875 else 876 return createFastRegisterAllocator(); 877 } 878 879 /// Find and instantiate the register allocation pass requested by this target 880 /// at the current optimization level. Different register allocators are 881 /// defined as separate passes because they may require different analysis. 882 /// 883 /// This helper ensures that the regalloc= option is always available, 884 /// even for targets that override the default allocator. 885 /// 886 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs, 887 /// this can be folded into addPass. 888 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) { 889 // Initialize the global default. 890 llvm::call_once(InitializeDefaultRegisterAllocatorFlag, 891 initializeDefaultRegisterAllocatorOnce); 892 893 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 894 if (Ctor != useDefaultRegisterAllocator) 895 return Ctor(); 896 897 // With no -regalloc= override, ask the target for a regalloc pass. 898 return createTargetRegisterAllocator(Optimized); 899 } 900 901 /// Return true if the default global register allocator is in use and 902 /// has not be overriden on the command line with '-regalloc=...' 903 bool TargetPassConfig::usingDefaultRegAlloc() const { 904 return RegAlloc.getNumOccurrences() == 0; 905 } 906 907 /// Add the minimum set of target-independent passes that are required for 908 /// register allocation. No coalescing or scheduling. 909 void TargetPassConfig::addFastRegAlloc(FunctionPass *RegAllocPass) { 910 addPass(&PHIEliminationID, false); 911 addPass(&TwoAddressInstructionPassID, false); 912 913 if (RegAllocPass) 914 addPass(RegAllocPass); 915 } 916 917 /// Add standard target-independent passes that are tightly coupled with 918 /// optimized register allocation, including coalescing, machine instruction 919 /// scheduling, and register allocation itself. 920 void TargetPassConfig::addOptimizedRegAlloc(FunctionPass *RegAllocPass) { 921 addPass(&DetectDeadLanesID, false); 922 923 addPass(&ProcessImplicitDefsID, false); 924 925 // LiveVariables currently requires pure SSA form. 926 // 927 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags, 928 // LiveVariables can be removed completely, and LiveIntervals can be directly 929 // computed. (We still either need to regenerate kill flags after regalloc, or 930 // preferably fix the scavenger to not depend on them). 931 addPass(&LiveVariablesID, false); 932 933 // Edge splitting is smarter with machine loop info. 934 addPass(&MachineLoopInfoID, false); 935 addPass(&PHIEliminationID, false); 936 937 // Eventually, we want to run LiveIntervals before PHI elimination. 938 if (EarlyLiveIntervals) 939 addPass(&LiveIntervalsID, false); 940 941 addPass(&TwoAddressInstructionPassID, false); 942 addPass(&RegisterCoalescerID); 943 944 // The machine scheduler may accidentally create disconnected components 945 // when moving subregister definitions around, avoid this by splitting them to 946 // separate vregs before. Splitting can also improve reg. allocation quality. 947 addPass(&RenameIndependentSubregsID); 948 949 // PreRA instruction scheduling. 950 addPass(&MachineSchedulerID); 951 952 if (RegAllocPass) { 953 // Add the selected register allocation pass. 954 addPass(RegAllocPass); 955 956 // Allow targets to change the register assignments before rewriting. 957 addPreRewrite(); 958 959 // Finally rewrite virtual registers. 960 addPass(&VirtRegRewriterID); 961 962 // Perform stack slot coloring and post-ra machine LICM. 963 // 964 // FIXME: Re-enable coloring with register when it's capable of adding 965 // kill markers. 966 addPass(&StackSlotColoringID); 967 968 // Run post-ra machine LICM to hoist reloads / remats. 969 // 970 // FIXME: can this move into MachineLateOptimization? 971 addPass(&PostRAMachineLICMID); 972 } 973 } 974 975 //===---------------------------------------------------------------------===// 976 /// Post RegAlloc Pass Configuration 977 //===---------------------------------------------------------------------===// 978 979 /// Add passes that optimize machine instructions after register allocation. 980 void TargetPassConfig::addMachineLateOptimization() { 981 // Branch folding must be run after regalloc and prolog/epilog insertion. 982 addPass(&BranchFolderPassID); 983 984 // Tail duplication. 985 // Note that duplicating tail just increases code size and degrades 986 // performance for targets that require Structured Control Flow. 987 // In addition it can also make CFG irreducible. Thus we disable it. 988 if (!TM->requiresStructuredCFG()) 989 addPass(&TailDuplicateID); 990 991 // Copy propagation. 992 addPass(&MachineCopyPropagationID); 993 } 994 995 /// Add standard GC passes. 996 bool TargetPassConfig::addGCPasses() { 997 addPass(&GCMachineCodeAnalysisID, false); 998 return true; 999 } 1000 1001 /// Add standard basic block placement passes. 1002 void TargetPassConfig::addBlockPlacement() { 1003 if (addPass(&MachineBlockPlacementID)) { 1004 // Run a separate pass to collect block placement statistics. 1005 if (EnableBlockPlacementStats) 1006 addPass(&MachineBlockPlacementStatsID); 1007 } 1008 } 1009 1010 //===---------------------------------------------------------------------===// 1011 /// GlobalISel Configuration 1012 //===---------------------------------------------------------------------===// 1013 1014 bool TargetPassConfig::isGlobalISelEnabled() const { 1015 return false; 1016 } 1017 1018 bool TargetPassConfig::isGlobalISelAbortEnabled() const { 1019 return EnableGlobalISelAbort == 1; 1020 } 1021 1022 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const { 1023 return EnableGlobalISelAbort == 2; 1024 } 1025