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 void llvm::registerCodeGenCallback(PassInstrumentationCallbacks &PIC, 508 LLVMTargetMachine &LLVMTM) { 509 510 // Register a callback for disabling passes. 511 PIC.registerShouldRunOptionalPassCallback([](StringRef P, Any) { 512 513 #define DISABLE_PASS(Option, Name) \ 514 if (Option && P.contains(#Name)) \ 515 return false; 516 DISABLE_PASS(DisableBlockPlacement, MachineBlockPlacementPass) 517 DISABLE_PASS(DisableBranchFold, BranchFolderPass) 518 DISABLE_PASS(DisableCopyProp, MachineCopyPropagationPass) 519 DISABLE_PASS(DisableEarlyIfConversion, EarlyIfConverterPass) 520 DISABLE_PASS(DisableEarlyTailDup, EarlyTailDuplicatePass) 521 DISABLE_PASS(DisableMachineCSE, MachineCSEPass) 522 DISABLE_PASS(DisableMachineDCE, DeadMachineInstructionElimPass) 523 DISABLE_PASS(DisableMachineLICM, EarlyMachineLICMPass) 524 DISABLE_PASS(DisableMachineSink, MachineSinkingPass) 525 DISABLE_PASS(DisablePostRAMachineLICM, MachineLICMPass) 526 DISABLE_PASS(DisablePostRAMachineSink, PostRAMachineSinkingPass) 527 DISABLE_PASS(DisablePostRASched, PostRASchedulerPass) 528 DISABLE_PASS(DisableSSC, StackSlotColoringPass) 529 DISABLE_PASS(DisableTailDuplicate, TailDuplicatePass) 530 531 return true; 532 }); 533 } 534 535 Expected<TargetPassConfig::StartStopInfo> 536 TargetPassConfig::getStartStopInfo(PassInstrumentationCallbacks &PIC) { 537 auto [StartBefore, StartBeforeInstanceNum] = 538 getPassNameAndInstanceNum(StartBeforeOpt); 539 auto [StartAfter, StartAfterInstanceNum] = 540 getPassNameAndInstanceNum(StartAfterOpt); 541 auto [StopBefore, StopBeforeInstanceNum] = 542 getPassNameAndInstanceNum(StopBeforeOpt); 543 auto [StopAfter, StopAfterInstanceNum] = 544 getPassNameAndInstanceNum(StopAfterOpt); 545 546 if (!StartBefore.empty() && !StartAfter.empty()) 547 return make_error<StringError>( 548 Twine(StartBeforeOptName) + " and " + StartAfterOptName + " specified!", 549 std::make_error_code(std::errc::invalid_argument)); 550 if (!StopBefore.empty() && !StopAfter.empty()) 551 return make_error<StringError>( 552 Twine(StopBeforeOptName) + " and " + StopAfterOptName + " specified!", 553 std::make_error_code(std::errc::invalid_argument)); 554 555 StartStopInfo Result; 556 Result.StartPass = StartBefore.empty() ? StartAfter : StartBefore; 557 Result.StopPass = StopBefore.empty() ? StopAfter : StopBefore; 558 Result.StartInstanceNum = 559 StartBefore.empty() ? StartAfterInstanceNum : StartBeforeInstanceNum; 560 Result.StopInstanceNum = 561 StopBefore.empty() ? StopAfterInstanceNum : StopBeforeInstanceNum; 562 Result.StartAfter = !StartAfter.empty(); 563 Result.StopAfter = !StopAfter.empty(); 564 Result.StartInstanceNum += Result.StartInstanceNum == 0; 565 Result.StopInstanceNum += Result.StopInstanceNum == 0; 566 return Result; 567 } 568 569 // Out of line constructor provides default values for pass options and 570 // registers all common codegen passes. 571 TargetPassConfig::TargetPassConfig(LLVMTargetMachine &TM, PassManagerBase &pm) 572 : ImmutablePass(ID), PM(&pm), TM(&TM) { 573 Impl = new PassConfigImpl(); 574 575 // Register all target independent codegen passes to activate their PassIDs, 576 // including this pass itself. 577 initializeCodeGen(*PassRegistry::getPassRegistry()); 578 579 // Also register alias analysis passes required by codegen passes. 580 initializeBasicAAWrapperPassPass(*PassRegistry::getPassRegistry()); 581 initializeAAResultsWrapperPassPass(*PassRegistry::getPassRegistry()); 582 583 if (EnableIPRA.getNumOccurrences()) 584 TM.Options.EnableIPRA = EnableIPRA; 585 else { 586 // If not explicitly specified, use target default. 587 TM.Options.EnableIPRA |= TM.useIPRA(); 588 } 589 590 if (TM.Options.EnableIPRA) 591 setRequiresCodeGenSCCOrder(); 592 593 if (EnableGlobalISelAbort.getNumOccurrences()) 594 TM.Options.GlobalISelAbort = EnableGlobalISelAbort; 595 596 setStartStopPasses(); 597 } 598 599 CodeGenOptLevel TargetPassConfig::getOptLevel() const { 600 return TM->getOptLevel(); 601 } 602 603 /// Insert InsertedPassID pass after TargetPassID. 604 void TargetPassConfig::insertPass(AnalysisID TargetPassID, 605 IdentifyingPassPtr InsertedPassID) { 606 assert(((!InsertedPassID.isInstance() && 607 TargetPassID != InsertedPassID.getID()) || 608 (InsertedPassID.isInstance() && 609 TargetPassID != InsertedPassID.getInstance()->getPassID())) && 610 "Insert a pass after itself!"); 611 Impl->InsertedPasses.emplace_back(TargetPassID, InsertedPassID); 612 } 613 614 /// createPassConfig - Create a pass configuration object to be used by 615 /// addPassToEmitX methods for generating a pipeline of CodeGen passes. 616 /// 617 /// Targets may override this to extend TargetPassConfig. 618 TargetPassConfig *LLVMTargetMachine::createPassConfig(PassManagerBase &PM) { 619 return new TargetPassConfig(*this, PM); 620 } 621 622 TargetPassConfig::TargetPassConfig() 623 : ImmutablePass(ID) { 624 report_fatal_error("Trying to construct TargetPassConfig without a target " 625 "machine. Scheduling a CodeGen pass without a target " 626 "triple set?"); 627 } 628 629 bool TargetPassConfig::willCompleteCodeGenPipeline() { 630 return StopBeforeOpt.empty() && StopAfterOpt.empty(); 631 } 632 633 bool TargetPassConfig::hasLimitedCodeGenPipeline() { 634 return !StartBeforeOpt.empty() || !StartAfterOpt.empty() || 635 !willCompleteCodeGenPipeline(); 636 } 637 638 std::string 639 TargetPassConfig::getLimitedCodeGenPipelineReason(const char *Separator) { 640 if (!hasLimitedCodeGenPipeline()) 641 return std::string(); 642 std::string Res; 643 static cl::opt<std::string> *PassNames[] = {&StartAfterOpt, &StartBeforeOpt, 644 &StopAfterOpt, &StopBeforeOpt}; 645 static const char *OptNames[] = {StartAfterOptName, StartBeforeOptName, 646 StopAfterOptName, StopBeforeOptName}; 647 bool IsFirst = true; 648 for (int Idx = 0; Idx < 4; ++Idx) 649 if (!PassNames[Idx]->empty()) { 650 if (!IsFirst) 651 Res += Separator; 652 IsFirst = false; 653 Res += OptNames[Idx]; 654 } 655 return Res; 656 } 657 658 // Helper to verify the analysis is really immutable. 659 void TargetPassConfig::setOpt(bool &Opt, bool Val) { 660 assert(!Initialized && "PassConfig is immutable"); 661 Opt = Val; 662 } 663 664 void TargetPassConfig::substitutePass(AnalysisID StandardID, 665 IdentifyingPassPtr TargetID) { 666 Impl->TargetPasses[StandardID] = TargetID; 667 } 668 669 IdentifyingPassPtr TargetPassConfig::getPassSubstitution(AnalysisID ID) const { 670 DenseMap<AnalysisID, IdentifyingPassPtr>::const_iterator 671 I = Impl->TargetPasses.find(ID); 672 if (I == Impl->TargetPasses.end()) 673 return ID; 674 return I->second; 675 } 676 677 bool TargetPassConfig::isPassSubstitutedOrOverridden(AnalysisID ID) const { 678 IdentifyingPassPtr TargetID = getPassSubstitution(ID); 679 IdentifyingPassPtr FinalPtr = overridePass(ID, TargetID); 680 return !FinalPtr.isValid() || FinalPtr.isInstance() || 681 FinalPtr.getID() != ID; 682 } 683 684 /// Add a pass to the PassManager if that pass is supposed to be run. If the 685 /// Started/Stopped flags indicate either that the compilation should start at 686 /// a later pass or that it should stop after an earlier pass, then do not add 687 /// the pass. Finally, compare the current pass against the StartAfter 688 /// and StopAfter options and change the Started/Stopped flags accordingly. 689 void TargetPassConfig::addPass(Pass *P) { 690 assert(!Initialized && "PassConfig is immutable"); 691 692 // Cache the Pass ID here in case the pass manager finds this pass is 693 // redundant with ones already scheduled / available, and deletes it. 694 // Fundamentally, once we add the pass to the manager, we no longer own it 695 // and shouldn't reference it. 696 AnalysisID PassID = P->getPassID(); 697 698 if (StartBefore == PassID && StartBeforeCount++ == StartBeforeInstanceNum) 699 Started = true; 700 if (StopBefore == PassID && StopBeforeCount++ == StopBeforeInstanceNum) 701 Stopped = true; 702 if (Started && !Stopped) { 703 if (AddingMachinePasses) { 704 // Construct banner message before PM->add() as that may delete the pass. 705 std::string Banner = 706 std::string("After ") + std::string(P->getPassName()); 707 addMachinePrePasses(); 708 PM->add(P); 709 addMachinePostPasses(Banner); 710 } else { 711 PM->add(P); 712 } 713 714 // Add the passes after the pass P if there is any. 715 for (const auto &IP : Impl->InsertedPasses) 716 if (IP.TargetPassID == PassID) 717 addPass(IP.getInsertedPass()); 718 } else { 719 delete P; 720 } 721 722 if (StopAfter == PassID && StopAfterCount++ == StopAfterInstanceNum) 723 Stopped = true; 724 725 if (StartAfter == PassID && StartAfterCount++ == StartAfterInstanceNum) 726 Started = true; 727 if (Stopped && !Started) 728 report_fatal_error("Cannot stop compilation after pass that is not run"); 729 } 730 731 /// Add a CodeGen pass at this point in the pipeline after checking for target 732 /// and command line overrides. 733 /// 734 /// addPass cannot return a pointer to the pass instance because is internal the 735 /// PassManager and the instance we create here may already be freed. 736 AnalysisID TargetPassConfig::addPass(AnalysisID PassID) { 737 IdentifyingPassPtr TargetID = getPassSubstitution(PassID); 738 IdentifyingPassPtr FinalPtr = overridePass(PassID, TargetID); 739 if (!FinalPtr.isValid()) 740 return nullptr; 741 742 Pass *P; 743 if (FinalPtr.isInstance()) 744 P = FinalPtr.getInstance(); 745 else { 746 P = Pass::createPass(FinalPtr.getID()); 747 if (!P) 748 llvm_unreachable("Pass ID not registered"); 749 } 750 AnalysisID FinalID = P->getPassID(); 751 addPass(P); // Ends the lifetime of P. 752 753 return FinalID; 754 } 755 756 void TargetPassConfig::printAndVerify(const std::string &Banner) { 757 addPrintPass(Banner); 758 addVerifyPass(Banner); 759 } 760 761 void TargetPassConfig::addPrintPass(const std::string &Banner) { 762 if (PrintAfterISel) 763 PM->add(createMachineFunctionPrinterPass(dbgs(), Banner)); 764 } 765 766 void TargetPassConfig::addVerifyPass(const std::string &Banner) { 767 bool Verify = VerifyMachineCode == cl::BOU_TRUE; 768 #ifdef EXPENSIVE_CHECKS 769 if (VerifyMachineCode == cl::BOU_UNSET) 770 Verify = TM->isMachineVerifierClean(); 771 #endif 772 if (Verify) 773 PM->add(createMachineVerifierPass(Banner)); 774 } 775 776 void TargetPassConfig::addDebugifyPass() { 777 PM->add(createDebugifyMachineModulePass()); 778 } 779 780 void TargetPassConfig::addStripDebugPass() { 781 PM->add(createStripDebugMachineModulePass(/*OnlyDebugified=*/true)); 782 } 783 784 void TargetPassConfig::addCheckDebugPass() { 785 PM->add(createCheckDebugMachineModulePass()); 786 } 787 788 void TargetPassConfig::addMachinePrePasses(bool AllowDebugify) { 789 if (AllowDebugify && DebugifyIsSafe && 790 (DebugifyAndStripAll == cl::BOU_TRUE || 791 DebugifyCheckAndStripAll == cl::BOU_TRUE)) 792 addDebugifyPass(); 793 } 794 795 void TargetPassConfig::addMachinePostPasses(const std::string &Banner) { 796 if (DebugifyIsSafe) { 797 if (DebugifyCheckAndStripAll == cl::BOU_TRUE) { 798 addCheckDebugPass(); 799 addStripDebugPass(); 800 } else if (DebugifyAndStripAll == cl::BOU_TRUE) 801 addStripDebugPass(); 802 } 803 addVerifyPass(Banner); 804 } 805 806 /// Add common target configurable passes that perform LLVM IR to IR transforms 807 /// following machine independent optimization. 808 void TargetPassConfig::addIRPasses() { 809 // Before running any passes, run the verifier to determine if the input 810 // coming from the front-end and/or optimizer is valid. 811 if (!DisableVerify) 812 addPass(createVerifierPass()); 813 814 if (getOptLevel() != CodeGenOptLevel::None) { 815 // Basic AliasAnalysis support. 816 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 817 // BasicAliasAnalysis wins if they disagree. This is intended to help 818 // support "obvious" type-punning idioms. 819 addPass(createTypeBasedAAWrapperPass()); 820 addPass(createScopedNoAliasAAWrapperPass()); 821 addPass(createBasicAAWrapperPass()); 822 823 // Run loop strength reduction before anything else. 824 if (!DisableLSR) { 825 addPass(createCanonicalizeFreezeInLoopsPass()); 826 addPass(createLoopStrengthReducePass()); 827 if (PrintLSR) 828 addPass(createPrintFunctionPass(dbgs(), 829 "\n\n*** Code after LSR ***\n")); 830 } 831 832 // The MergeICmpsPass tries to create memcmp calls by grouping sequences of 833 // loads and compares. ExpandMemCmpPass then tries to expand those calls 834 // into optimally-sized loads and compares. The transforms are enabled by a 835 // target lowering hook. 836 if (!DisableMergeICmps) 837 addPass(createMergeICmpsLegacyPass()); 838 addPass(createExpandMemCmpLegacyPass()); 839 } 840 841 // Run GC lowering passes for builtin collectors 842 // TODO: add a pass insertion point here 843 addPass(&GCLoweringID); 844 addPass(&ShadowStackGCLoweringID); 845 addPass(createLowerConstantIntrinsicsPass()); 846 847 // For MachO, lower @llvm.global_dtors into @llvm.global_ctors with 848 // __cxa_atexit() calls to avoid emitting the deprecated __mod_term_func. 849 if (TM->getTargetTriple().isOSBinFormatMachO() && 850 !DisableAtExitBasedGlobalDtorLowering) 851 addPass(createLowerGlobalDtorsLegacyPass()); 852 853 // Make sure that no unreachable blocks are instruction selected. 854 addPass(createUnreachableBlockEliminationPass()); 855 856 // Prepare expensive constants for SelectionDAG. 857 if (getOptLevel() != CodeGenOptLevel::None && !DisableConstantHoisting) 858 addPass(createConstantHoistingPass()); 859 860 if (getOptLevel() != CodeGenOptLevel::None) 861 addPass(createReplaceWithVeclibLegacyPass()); 862 863 if (getOptLevel() != CodeGenOptLevel::None && !DisablePartialLibcallInlining) 864 addPass(createPartiallyInlineLibCallsPass()); 865 866 // Expand vector predication intrinsics into standard IR instructions. 867 // This pass has to run before ScalarizeMaskedMemIntrin and ExpandReduction 868 // passes since it emits those kinds of intrinsics. 869 addPass(createExpandVectorPredicationPass()); 870 871 // Add scalarization of target's unsupported masked memory intrinsics pass. 872 // the unsupported intrinsic will be replaced with a chain of basic blocks, 873 // that stores/loads element one-by-one if the appropriate mask bit is set. 874 addPass(createScalarizeMaskedMemIntrinLegacyPass()); 875 876 // Expand reduction intrinsics into shuffle sequences if the target wants to. 877 // Allow disabling it for testing purposes. 878 if (!DisableExpandReductions) 879 addPass(createExpandReductionsPass()); 880 881 if (getOptLevel() != CodeGenOptLevel::None) 882 addPass(createTLSVariableHoistPass()); 883 884 // Convert conditional moves to conditional jumps when profitable. 885 if (getOptLevel() != CodeGenOptLevel::None && !DisableSelectOptimize) 886 addPass(createSelectOptimizePass()); 887 } 888 889 /// Turn exception handling constructs into something the code generators can 890 /// handle. 891 void TargetPassConfig::addPassesToHandleExceptions() { 892 const MCAsmInfo *MCAI = TM->getMCAsmInfo(); 893 assert(MCAI && "No MCAsmInfo"); 894 switch (MCAI->getExceptionHandlingType()) { 895 case ExceptionHandling::SjLj: 896 // SjLj piggy-backs on dwarf for this bit. The cleanups done apply to both 897 // Dwarf EH prepare needs to be run after SjLj prepare. Otherwise, 898 // catch info can get misplaced when a selector ends up more than one block 899 // removed from the parent invoke(s). This could happen when a landing 900 // pad is shared by multiple invokes and is also a target of a normal 901 // edge from elsewhere. 902 addPass(createSjLjEHPreparePass(TM)); 903 [[fallthrough]]; 904 case ExceptionHandling::DwarfCFI: 905 case ExceptionHandling::ARM: 906 case ExceptionHandling::AIX: 907 case ExceptionHandling::ZOS: 908 addPass(createDwarfEHPass(getOptLevel())); 909 break; 910 case ExceptionHandling::WinEH: 911 // We support using both GCC-style and MSVC-style exceptions on Windows, so 912 // add both preparation passes. Each pass will only actually run if it 913 // recognizes the personality function. 914 addPass(createWinEHPass()); 915 addPass(createDwarfEHPass(getOptLevel())); 916 break; 917 case ExceptionHandling::Wasm: 918 // Wasm EH uses Windows EH instructions, but it does not need to demote PHIs 919 // on catchpads and cleanuppads because it does not outline them into 920 // funclets. Catchswitch blocks are not lowered in SelectionDAG, so we 921 // should remove PHIs there. 922 addPass(createWinEHPass(/*DemoteCatchSwitchPHIOnly=*/false)); 923 addPass(createWasmEHPass()); 924 break; 925 case ExceptionHandling::None: 926 addPass(createLowerInvokePass()); 927 928 // The lower invoke pass may create unreachable code. Remove it. 929 addPass(createUnreachableBlockEliminationPass()); 930 break; 931 } 932 } 933 934 /// Add pass to prepare the LLVM IR for code generation. This should be done 935 /// before exception handling preparation passes. 936 void TargetPassConfig::addCodeGenPrepare() { 937 if (getOptLevel() != CodeGenOptLevel::None && !DisableCGP) 938 addPass(createCodeGenPrepareLegacyPass()); 939 } 940 941 /// Add common passes that perform LLVM IR to IR transforms in preparation for 942 /// instruction selection. 943 void TargetPassConfig::addISelPrepare() { 944 addPreISel(); 945 946 // Force codegen to run according to the callgraph. 947 if (requiresCodeGenSCCOrder()) 948 addPass(new DummyCGSCCPass); 949 950 addPass(createCallBrPass()); 951 952 // Add both the safe stack and the stack protection passes: each of them will 953 // only protect functions that have corresponding attributes. 954 addPass(createSafeStackPass()); 955 addPass(createStackProtectorPass()); 956 957 if (PrintISelInput) 958 addPass(createPrintFunctionPass( 959 dbgs(), "\n\n*** Final LLVM Code input to ISel ***\n")); 960 961 // All passes which modify the LLVM IR are now complete; run the verifier 962 // to ensure that the IR is valid. 963 if (!DisableVerify) 964 addPass(createVerifierPass()); 965 } 966 967 bool TargetPassConfig::addCoreISelPasses() { 968 // Enable FastISel with -fast-isel, but allow that to be overridden. 969 TM->setO0WantsFastISel(EnableFastISelOption != cl::BOU_FALSE); 970 971 // Determine an instruction selector. 972 enum class SelectorType { SelectionDAG, FastISel, GlobalISel }; 973 SelectorType Selector; 974 975 if (EnableFastISelOption == cl::BOU_TRUE) 976 Selector = SelectorType::FastISel; 977 else if (EnableGlobalISelOption == cl::BOU_TRUE || 978 (TM->Options.EnableGlobalISel && 979 EnableGlobalISelOption != cl::BOU_FALSE)) 980 Selector = SelectorType::GlobalISel; 981 else if (TM->getOptLevel() == CodeGenOptLevel::None && 982 TM->getO0WantsFastISel()) 983 Selector = SelectorType::FastISel; 984 else 985 Selector = SelectorType::SelectionDAG; 986 987 // Set consistently TM->Options.EnableFastISel and EnableGlobalISel. 988 if (Selector == SelectorType::FastISel) { 989 TM->setFastISel(true); 990 TM->setGlobalISel(false); 991 } else if (Selector == SelectorType::GlobalISel) { 992 TM->setFastISel(false); 993 TM->setGlobalISel(true); 994 } 995 996 // FIXME: Injecting into the DAGISel pipeline seems to cause issues with 997 // analyses needing to be re-run. This can result in being unable to 998 // schedule passes (particularly with 'Function Alias Analysis 999 // Results'). It's not entirely clear why but AFAICT this seems to be 1000 // due to one FunctionPassManager not being able to use analyses from a 1001 // previous one. As we're injecting a ModulePass we break the usual 1002 // pass manager into two. GlobalISel with the fallback path disabled 1003 // and -run-pass seem to be unaffected. The majority of GlobalISel 1004 // testing uses -run-pass so this probably isn't too bad. 1005 SaveAndRestore SavedDebugifyIsSafe(DebugifyIsSafe); 1006 if (Selector != SelectorType::GlobalISel || !isGlobalISelAbortEnabled()) 1007 DebugifyIsSafe = false; 1008 1009 // Add instruction selector passes. 1010 if (Selector == SelectorType::GlobalISel) { 1011 SaveAndRestore SavedAddingMachinePasses(AddingMachinePasses, true); 1012 if (addIRTranslator()) 1013 return true; 1014 1015 addPreLegalizeMachineIR(); 1016 1017 if (addLegalizeMachineIR()) 1018 return true; 1019 1020 // Before running the register bank selector, ask the target if it 1021 // wants to run some passes. 1022 addPreRegBankSelect(); 1023 1024 if (addRegBankSelect()) 1025 return true; 1026 1027 addPreGlobalInstructionSelect(); 1028 1029 if (addGlobalInstructionSelect()) 1030 return true; 1031 1032 // Pass to reset the MachineFunction if the ISel failed. 1033 addPass(createResetMachineFunctionPass( 1034 reportDiagnosticWhenGlobalISelFallback(), isGlobalISelAbortEnabled())); 1035 1036 // Provide a fallback path when we do not want to abort on 1037 // not-yet-supported input. 1038 if (!isGlobalISelAbortEnabled() && addInstSelector()) 1039 return true; 1040 1041 } else if (addInstSelector()) 1042 return true; 1043 1044 // Expand pseudo-instructions emitted by ISel. Don't run the verifier before 1045 // FinalizeISel. 1046 addPass(&FinalizeISelID); 1047 1048 // Print the instruction selected machine code... 1049 printAndVerify("After Instruction Selection"); 1050 1051 return false; 1052 } 1053 1054 bool TargetPassConfig::addISelPasses() { 1055 if (TM->useEmulatedTLS()) 1056 addPass(createLowerEmuTLSPass()); 1057 1058 PM->add(createTargetTransformInfoWrapperPass(TM->getTargetIRAnalysis())); 1059 addPass(createPreISelIntrinsicLoweringPass()); 1060 addPass(createExpandLargeDivRemPass()); 1061 addPass(createExpandLargeFpConvertPass()); 1062 addIRPasses(); 1063 addCodeGenPrepare(); 1064 addPassesToHandleExceptions(); 1065 addISelPrepare(); 1066 1067 return addCoreISelPasses(); 1068 } 1069 1070 /// -regalloc=... command line option. 1071 static FunctionPass *useDefaultRegisterAllocator() { return nullptr; } 1072 static cl::opt<RegisterRegAlloc::FunctionPassCtor, false, 1073 RegisterPassParser<RegisterRegAlloc>> 1074 RegAlloc("regalloc", cl::Hidden, cl::init(&useDefaultRegisterAllocator), 1075 cl::desc("Register allocator to use")); 1076 1077 /// Add the complete set of target-independent postISel code generator passes. 1078 /// 1079 /// This can be read as the standard order of major LLVM CodeGen stages. Stages 1080 /// with nontrivial configuration or multiple passes are broken out below in 1081 /// add%Stage routines. 1082 /// 1083 /// Any TargetPassConfig::addXX routine may be overriden by the Target. The 1084 /// addPre/Post methods with empty header implementations allow injecting 1085 /// target-specific fixups just before or after major stages. Additionally, 1086 /// targets have the flexibility to change pass order within a stage by 1087 /// overriding default implementation of add%Stage routines below. Each 1088 /// technique has maintainability tradeoffs because alternate pass orders are 1089 /// not well supported. addPre/Post works better if the target pass is easily 1090 /// tied to a common pass. But if it has subtle dependencies on multiple passes, 1091 /// the target should override the stage instead. 1092 /// 1093 /// TODO: We could use a single addPre/Post(ID) hook to allow pass injection 1094 /// before/after any target-independent pass. But it's currently overkill. 1095 void TargetPassConfig::addMachinePasses() { 1096 AddingMachinePasses = true; 1097 1098 // Add passes that optimize machine instructions in SSA form. 1099 if (getOptLevel() != CodeGenOptLevel::None) { 1100 addMachineSSAOptimization(); 1101 } else { 1102 // If the target requests it, assign local variables to stack slots relative 1103 // to one another and simplify frame index references where possible. 1104 addPass(&LocalStackSlotAllocationID); 1105 } 1106 1107 if (TM->Options.EnableIPRA) 1108 addPass(createRegUsageInfoPropPass()); 1109 1110 // Run pre-ra passes. 1111 addPreRegAlloc(); 1112 1113 // Debugifying the register allocator passes seems to provoke some 1114 // non-determinism that affects CodeGen and there doesn't seem to be a point 1115 // where it becomes safe again so stop debugifying here. 1116 DebugifyIsSafe = false; 1117 1118 // Add a FSDiscriminator pass right before RA, so that we could get 1119 // more precise SampleFDO profile for RA. 1120 if (EnableFSDiscriminator) { 1121 addPass(createMIRAddFSDiscriminatorsPass( 1122 sampleprof::FSDiscriminatorPass::Pass1)); 1123 const std::string ProfileFile = getFSProfileFile(TM); 1124 if (!ProfileFile.empty() && !DisableRAFSProfileLoader) 1125 addPass(createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM), 1126 sampleprof::FSDiscriminatorPass::Pass1, 1127 nullptr)); 1128 } 1129 1130 // Run register allocation and passes that are tightly coupled with it, 1131 // including phi elimination and scheduling. 1132 if (getOptimizeRegAlloc()) 1133 addOptimizedRegAlloc(); 1134 else 1135 addFastRegAlloc(); 1136 1137 // Run post-ra passes. 1138 addPostRegAlloc(); 1139 1140 addPass(&RemoveRedundantDebugValuesID); 1141 1142 addPass(&FixupStatepointCallerSavedID); 1143 1144 // Insert prolog/epilog code. Eliminate abstract frame index references... 1145 if (getOptLevel() != CodeGenOptLevel::None) { 1146 addPass(&PostRAMachineSinkingID); 1147 addPass(&ShrinkWrapID); 1148 } 1149 1150 // Prolog/Epilog inserter needs a TargetMachine to instantiate. But only 1151 // do so if it hasn't been disabled, substituted, or overridden. 1152 if (!isPassSubstitutedOrOverridden(&PrologEpilogCodeInserterID)) 1153 addPass(createPrologEpilogInserterPass()); 1154 1155 /// Add passes that optimize machine instructions after register allocation. 1156 if (getOptLevel() != CodeGenOptLevel::None) 1157 addMachineLateOptimization(); 1158 1159 // Expand pseudo instructions before second scheduling pass. 1160 addPass(&ExpandPostRAPseudosID); 1161 1162 // Run pre-sched2 passes. 1163 addPreSched2(); 1164 1165 if (EnableImplicitNullChecks) 1166 addPass(&ImplicitNullChecksID); 1167 1168 // Second pass scheduler. 1169 // Let Target optionally insert this pass by itself at some other 1170 // point. 1171 if (getOptLevel() != CodeGenOptLevel::None && 1172 !TM->targetSchedulesPostRAScheduling()) { 1173 if (MISchedPostRA) 1174 addPass(&PostMachineSchedulerID); 1175 else 1176 addPass(&PostRASchedulerID); 1177 } 1178 1179 // GC 1180 addGCPasses(); 1181 1182 // Basic block placement. 1183 if (getOptLevel() != CodeGenOptLevel::None) 1184 addBlockPlacement(); 1185 1186 // Insert before XRay Instrumentation. 1187 addPass(&FEntryInserterID); 1188 1189 addPass(&XRayInstrumentationID); 1190 addPass(&PatchableFunctionID); 1191 1192 addPreEmitPass(); 1193 1194 if (TM->Options.EnableIPRA) 1195 // Collect register usage information and produce a register mask of 1196 // clobbered registers, to be used to optimize call sites. 1197 addPass(createRegUsageInfoCollector()); 1198 1199 // FIXME: Some backends are incompatible with running the verifier after 1200 // addPreEmitPass. Maybe only pass "false" here for those targets? 1201 addPass(&FuncletLayoutID); 1202 1203 addPass(&StackMapLivenessID); 1204 addPass(&LiveDebugValuesID); 1205 addPass(&MachineSanitizerBinaryMetadataID); 1206 1207 if (TM->Options.EnableMachineOutliner && 1208 getOptLevel() != CodeGenOptLevel::None && 1209 EnableMachineOutliner != RunOutliner::NeverOutline) { 1210 bool RunOnAllFunctions = 1211 (EnableMachineOutliner == RunOutliner::AlwaysOutline); 1212 bool AddOutliner = 1213 RunOnAllFunctions || TM->Options.SupportsDefaultOutlining; 1214 if (AddOutliner) 1215 addPass(createMachineOutlinerPass(RunOnAllFunctions)); 1216 } 1217 1218 if (GCEmptyBlocks) 1219 addPass(llvm::createGCEmptyBasicBlocksPass()); 1220 1221 if (EnableFSDiscriminator) 1222 addPass(createMIRAddFSDiscriminatorsPass( 1223 sampleprof::FSDiscriminatorPass::PassLast)); 1224 1225 // Machine function splitter uses the basic block sections feature. Both 1226 // cannot be enabled at the same time. Basic block sections takes precedence. 1227 // FIXME: In principle, BasicBlockSection::Labels and splitting can used 1228 // together. Update this check once we have addressed any issues. 1229 if (TM->getBBSectionsType() != llvm::BasicBlockSection::None) { 1230 if (TM->getBBSectionsType() == llvm::BasicBlockSection::List) { 1231 addPass(llvm::createBasicBlockSectionsProfileReaderWrapperPass( 1232 TM->getBBSectionsFuncListBuf())); 1233 addPass(llvm::createBasicBlockPathCloningPass()); 1234 } 1235 addPass(llvm::createBasicBlockSectionsPass()); 1236 } else if (TM->Options.EnableMachineFunctionSplitter || 1237 EnableMachineFunctionSplitter) { 1238 const std::string ProfileFile = getFSProfileFile(TM); 1239 if (!ProfileFile.empty()) { 1240 if (EnableFSDiscriminator) { 1241 addPass(createMIRProfileLoaderPass( 1242 ProfileFile, getFSRemappingFile(TM), 1243 sampleprof::FSDiscriminatorPass::PassLast, nullptr)); 1244 } else { 1245 // Sample profile is given, but FSDiscriminator is not 1246 // enabled, this may result in performance regression. 1247 WithColor::warning() 1248 << "Using AutoFDO without FSDiscriminator for MFS may regress " 1249 "performance.\n"; 1250 } 1251 } 1252 addPass(createMachineFunctionSplitterPass()); 1253 } 1254 1255 addPostBBSections(); 1256 1257 if (!DisableCFIFixup && TM->Options.EnableCFIFixup) 1258 addPass(createCFIFixup()); 1259 1260 PM->add(createStackFrameLayoutAnalysisPass()); 1261 1262 // Add passes that directly emit MI after all other MI passes. 1263 addPreEmitPass2(); 1264 1265 AddingMachinePasses = false; 1266 } 1267 1268 /// Add passes that optimize machine instructions in SSA form. 1269 void TargetPassConfig::addMachineSSAOptimization() { 1270 // Pre-ra tail duplication. 1271 addPass(&EarlyTailDuplicateID); 1272 1273 // Optimize PHIs before DCE: removing dead PHI cycles may make more 1274 // instructions dead. 1275 addPass(&OptimizePHIsID); 1276 1277 // This pass merges large allocas. StackSlotColoring is a different pass 1278 // which merges spill slots. 1279 addPass(&StackColoringID); 1280 1281 // If the target requests it, assign local variables to stack slots relative 1282 // to one another and simplify frame index references where possible. 1283 addPass(&LocalStackSlotAllocationID); 1284 1285 // With optimization, dead code should already be eliminated. However 1286 // there is one known exception: lowered code for arguments that are only 1287 // used by tail calls, where the tail calls reuse the incoming stack 1288 // arguments directly (see t11 in test/CodeGen/X86/sibcall.ll). 1289 addPass(&DeadMachineInstructionElimID); 1290 1291 // Allow targets to insert passes that improve instruction level parallelism, 1292 // like if-conversion. Such passes will typically need dominator trees and 1293 // loop info, just like LICM and CSE below. 1294 addILPOpts(); 1295 1296 addPass(&EarlyMachineLICMID); 1297 addPass(&MachineCSEID); 1298 1299 addPass(&MachineSinkingID); 1300 1301 addPass(&PeepholeOptimizerID); 1302 // Clean-up the dead code that may have been generated by peephole 1303 // rewriting. 1304 addPass(&DeadMachineInstructionElimID); 1305 } 1306 1307 //===---------------------------------------------------------------------===// 1308 /// Register Allocation Pass Configuration 1309 //===---------------------------------------------------------------------===// 1310 1311 bool TargetPassConfig::getOptimizeRegAlloc() const { 1312 switch (OptimizeRegAlloc) { 1313 case cl::BOU_UNSET: 1314 return getOptLevel() != CodeGenOptLevel::None; 1315 case cl::BOU_TRUE: return true; 1316 case cl::BOU_FALSE: return false; 1317 } 1318 llvm_unreachable("Invalid optimize-regalloc state"); 1319 } 1320 1321 /// A dummy default pass factory indicates whether the register allocator is 1322 /// overridden on the command line. 1323 static llvm::once_flag InitializeDefaultRegisterAllocatorFlag; 1324 1325 static RegisterRegAlloc 1326 defaultRegAlloc("default", 1327 "pick register allocator based on -O option", 1328 useDefaultRegisterAllocator); 1329 1330 static void initializeDefaultRegisterAllocatorOnce() { 1331 if (!RegisterRegAlloc::getDefault()) 1332 RegisterRegAlloc::setDefault(RegAlloc); 1333 } 1334 1335 /// Instantiate the default register allocator pass for this target for either 1336 /// the optimized or unoptimized allocation path. This will be added to the pass 1337 /// manager by addFastRegAlloc in the unoptimized case or addOptimizedRegAlloc 1338 /// in the optimized case. 1339 /// 1340 /// A target that uses the standard regalloc pass order for fast or optimized 1341 /// allocation may still override this for per-target regalloc 1342 /// selection. But -regalloc=... always takes precedence. 1343 FunctionPass *TargetPassConfig::createTargetRegisterAllocator(bool Optimized) { 1344 if (Optimized) 1345 return createGreedyRegisterAllocator(); 1346 else 1347 return createFastRegisterAllocator(); 1348 } 1349 1350 /// Find and instantiate the register allocation pass requested by this target 1351 /// at the current optimization level. Different register allocators are 1352 /// defined as separate passes because they may require different analysis. 1353 /// 1354 /// This helper ensures that the regalloc= option is always available, 1355 /// even for targets that override the default allocator. 1356 /// 1357 /// FIXME: When MachinePassRegistry register pass IDs instead of function ptrs, 1358 /// this can be folded into addPass. 1359 FunctionPass *TargetPassConfig::createRegAllocPass(bool Optimized) { 1360 // Initialize the global default. 1361 llvm::call_once(InitializeDefaultRegisterAllocatorFlag, 1362 initializeDefaultRegisterAllocatorOnce); 1363 1364 RegisterRegAlloc::FunctionPassCtor Ctor = RegisterRegAlloc::getDefault(); 1365 if (Ctor != useDefaultRegisterAllocator) 1366 return Ctor(); 1367 1368 // With no -regalloc= override, ask the target for a regalloc pass. 1369 return createTargetRegisterAllocator(Optimized); 1370 } 1371 1372 bool TargetPassConfig::isCustomizedRegAlloc() { 1373 return RegAlloc != 1374 (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator; 1375 } 1376 1377 bool TargetPassConfig::addRegAssignAndRewriteFast() { 1378 if (RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&useDefaultRegisterAllocator && 1379 RegAlloc != (RegisterRegAlloc::FunctionPassCtor)&createFastRegisterAllocator) 1380 report_fatal_error("Must use fast (default) register allocator for unoptimized regalloc."); 1381 1382 addPass(createRegAllocPass(false)); 1383 1384 // Allow targets to change the register assignments after 1385 // fast register allocation. 1386 addPostFastRegAllocRewrite(); 1387 return true; 1388 } 1389 1390 bool TargetPassConfig::addRegAssignAndRewriteOptimized() { 1391 // Add the selected register allocation pass. 1392 addPass(createRegAllocPass(true)); 1393 1394 // Allow targets to change the register assignments before rewriting. 1395 addPreRewrite(); 1396 1397 // Finally rewrite virtual registers. 1398 addPass(&VirtRegRewriterID); 1399 1400 // Regalloc scoring for ML-driven eviction - noop except when learning a new 1401 // eviction policy. 1402 addPass(createRegAllocScoringPass()); 1403 return true; 1404 } 1405 1406 /// Return true if the default global register allocator is in use and 1407 /// has not be overriden on the command line with '-regalloc=...' 1408 bool TargetPassConfig::usingDefaultRegAlloc() const { 1409 return RegAlloc.getNumOccurrences() == 0; 1410 } 1411 1412 /// Add the minimum set of target-independent passes that are required for 1413 /// register allocation. No coalescing or scheduling. 1414 void TargetPassConfig::addFastRegAlloc() { 1415 addPass(&PHIEliminationID); 1416 addPass(&TwoAddressInstructionPassID); 1417 1418 addRegAssignAndRewriteFast(); 1419 } 1420 1421 /// Add standard target-independent passes that are tightly coupled with 1422 /// optimized register allocation, including coalescing, machine instruction 1423 /// scheduling, and register allocation itself. 1424 void TargetPassConfig::addOptimizedRegAlloc() { 1425 addPass(&DetectDeadLanesID); 1426 1427 addPass(&ProcessImplicitDefsID); 1428 1429 // LiveVariables currently requires pure SSA form. 1430 // 1431 // FIXME: Once TwoAddressInstruction pass no longer uses kill flags, 1432 // LiveVariables can be removed completely, and LiveIntervals can be directly 1433 // computed. (We still either need to regenerate kill flags after regalloc, or 1434 // preferably fix the scavenger to not depend on them). 1435 // FIXME: UnreachableMachineBlockElim is a dependant pass of LiveVariables. 1436 // When LiveVariables is removed this has to be removed/moved either. 1437 // Explicit addition of UnreachableMachineBlockElim allows stopping before or 1438 // after it with -stop-before/-stop-after. 1439 addPass(&UnreachableMachineBlockElimID); 1440 addPass(&LiveVariablesID); 1441 1442 // Edge splitting is smarter with machine loop info. 1443 addPass(&MachineLoopInfoID); 1444 addPass(&PHIEliminationID); 1445 1446 // Eventually, we want to run LiveIntervals before PHI elimination. 1447 if (EarlyLiveIntervals) 1448 addPass(&LiveIntervalsID); 1449 1450 addPass(&TwoAddressInstructionPassID); 1451 addPass(&RegisterCoalescerID); 1452 1453 // The machine scheduler may accidentally create disconnected components 1454 // when moving subregister definitions around, avoid this by splitting them to 1455 // separate vregs before. Splitting can also improve reg. allocation quality. 1456 addPass(&RenameIndependentSubregsID); 1457 1458 // PreRA instruction scheduling. 1459 addPass(&MachineSchedulerID); 1460 1461 if (addRegAssignAndRewriteOptimized()) { 1462 // Perform stack slot coloring and post-ra machine LICM. 1463 addPass(&StackSlotColoringID); 1464 1465 // Allow targets to expand pseudo instructions depending on the choice of 1466 // registers before MachineCopyPropagation. 1467 addPostRewrite(); 1468 1469 // Copy propagate to forward register uses and try to eliminate COPYs that 1470 // were not coalesced. 1471 addPass(&MachineCopyPropagationID); 1472 1473 // Run post-ra machine LICM to hoist reloads / remats. 1474 // 1475 // FIXME: can this move into MachineLateOptimization? 1476 addPass(&MachineLICMID); 1477 } 1478 } 1479 1480 //===---------------------------------------------------------------------===// 1481 /// Post RegAlloc Pass Configuration 1482 //===---------------------------------------------------------------------===// 1483 1484 /// Add passes that optimize machine instructions after register allocation. 1485 void TargetPassConfig::addMachineLateOptimization() { 1486 // Cleanup of redundant immediate/address loads. 1487 addPass(&MachineLateInstrsCleanupID); 1488 1489 // Branch folding must be run after regalloc and prolog/epilog insertion. 1490 addPass(&BranchFolderPassID); 1491 1492 // Tail duplication. 1493 // Note that duplicating tail just increases code size and degrades 1494 // performance for targets that require Structured Control Flow. 1495 // In addition it can also make CFG irreducible. Thus we disable it. 1496 if (!TM->requiresStructuredCFG()) 1497 addPass(&TailDuplicateID); 1498 1499 // Copy propagation. 1500 addPass(&MachineCopyPropagationID); 1501 } 1502 1503 /// Add standard GC passes. 1504 bool TargetPassConfig::addGCPasses() { 1505 addPass(&GCMachineCodeAnalysisID); 1506 return true; 1507 } 1508 1509 /// Add standard basic block placement passes. 1510 void TargetPassConfig::addBlockPlacement() { 1511 if (EnableFSDiscriminator) { 1512 addPass(createMIRAddFSDiscriminatorsPass( 1513 sampleprof::FSDiscriminatorPass::Pass2)); 1514 const std::string ProfileFile = getFSProfileFile(TM); 1515 if (!ProfileFile.empty() && !DisableLayoutFSProfileLoader) 1516 addPass(createMIRProfileLoaderPass(ProfileFile, getFSRemappingFile(TM), 1517 sampleprof::FSDiscriminatorPass::Pass2, 1518 nullptr)); 1519 } 1520 if (addPass(&MachineBlockPlacementID)) { 1521 // Run a separate pass to collect block placement statistics. 1522 if (EnableBlockPlacementStats) 1523 addPass(&MachineBlockPlacementStatsID); 1524 } 1525 } 1526 1527 //===---------------------------------------------------------------------===// 1528 /// GlobalISel Configuration 1529 //===---------------------------------------------------------------------===// 1530 bool TargetPassConfig::isGlobalISelAbortEnabled() const { 1531 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::Enable; 1532 } 1533 1534 bool TargetPassConfig::reportDiagnosticWhenGlobalISelFallback() const { 1535 return TM->Options.GlobalISelAbort == GlobalISelAbortMode::DisableWithDiag; 1536 } 1537 1538 bool TargetPassConfig::isGISelCSEEnabled() const { 1539 return true; 1540 } 1541 1542 std::unique_ptr<CSEConfigBase> TargetPassConfig::getCSEConfig() const { 1543 return std::make_unique<CSEConfigBase>(); 1544 } 1545