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