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