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