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