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