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