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