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