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