1 //===- PassManagerBuilder.cpp - Build Standard Pass -----------------------===// 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 the PassManagerBuilder class, which is used to set up a 10 // "standard" optimization sequence suitable for languages like C and C++. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "llvm/Transforms/IPO/PassManagerBuilder.h" 15 #include "llvm-c/Transforms/PassManagerBuilder.h" 16 #include "llvm/ADT/STLExtras.h" 17 #include "llvm/ADT/SmallVector.h" 18 #include "llvm/Analysis/BasicAliasAnalysis.h" 19 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 20 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 21 #include "llvm/Analysis/GlobalsModRef.h" 22 #include "llvm/Analysis/InlineCost.h" 23 #include "llvm/Analysis/Passes.h" 24 #include "llvm/Analysis/ScopedNoAliasAA.h" 25 #include "llvm/Analysis/TargetLibraryInfo.h" 26 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 27 #include "llvm/IR/DataLayout.h" 28 #include "llvm/IR/LegacyPassManager.h" 29 #include "llvm/IR/Verifier.h" 30 #include "llvm/Support/CommandLine.h" 31 #include "llvm/Support/ManagedStatic.h" 32 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 33 #include "llvm/Transforms/IPO.h" 34 #include "llvm/Transforms/IPO/Attributor.h" 35 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 36 #include "llvm/Transforms/IPO/FunctionAttrs.h" 37 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 38 #include "llvm/Transforms/InstCombine/InstCombine.h" 39 #include "llvm/Transforms/Instrumentation.h" 40 #include "llvm/Transforms/Scalar.h" 41 #include "llvm/Transforms/Scalar/GVN.h" 42 #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 43 #include "llvm/Transforms/Scalar/LICM.h" 44 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 45 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 46 #include "llvm/Transforms/Utils.h" 47 #include "llvm/Transforms/Vectorize.h" 48 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 49 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 50 #include "llvm/Transforms/Vectorize/VectorCombine.h" 51 52 using namespace llvm; 53 54 cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::init(false), 55 cl::Hidden, cl::ZeroOrMore, 56 cl::desc("Run Partial inlinining pass")); 57 58 static cl::opt<bool> 59 UseGVNAfterVectorization("use-gvn-after-vectorization", 60 cl::init(false), cl::Hidden, 61 cl::desc("Run GVN instead of Early CSE after vectorization passes")); 62 63 cl::opt<bool> ExtraVectorizerPasses( 64 "extra-vectorizer-passes", cl::init(false), cl::Hidden, 65 cl::desc("Run cleanup optimization passes after vectorization.")); 66 67 static cl::opt<bool> 68 RunLoopRerolling("reroll-loops", cl::Hidden, 69 cl::desc("Run the loop rerolling pass")); 70 71 cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, 72 cl::desc("Run the NewGVN pass")); 73 74 // Experimental option to use CFL-AA 75 enum class CFLAAType { None, Steensgaard, Andersen, Both }; 76 static cl::opt<::CFLAAType> 77 UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden, 78 cl::desc("Enable the new, experimental CFL alias analysis"), 79 cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"), 80 clEnumValN(::CFLAAType::Steensgaard, "steens", 81 "Enable unification-based CFL-AA"), 82 clEnumValN(::CFLAAType::Andersen, "anders", 83 "Enable inclusion-based CFL-AA"), 84 clEnumValN(::CFLAAType::Both, "both", 85 "Enable both variants of CFL-AA"))); 86 87 cl::opt<bool> EnableLoopInterchange( 88 "enable-loopinterchange", cl::init(false), cl::Hidden, 89 cl::desc("Enable the experimental LoopInterchange Pass")); 90 91 cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), 92 cl::Hidden, 93 cl::desc("Enable Unroll And Jam Pass")); 94 95 cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false), 96 cl::Hidden, 97 cl::desc("Enable the LoopFlatten Pass")); 98 99 static cl::opt<bool> 100 EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden, 101 cl::desc("Enable preparation for ThinLTO.")); 102 103 static cl::opt<bool> 104 EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden, 105 cl::desc("Enable performing ThinLTO.")); 106 107 cl::opt<bool> EnableHotColdSplit("hot-cold-split", cl::init(false), 108 cl::ZeroOrMore, cl::desc("Enable hot-cold splitting pass")); 109 110 cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden, 111 cl::desc("Enable ir outliner pass")); 112 113 static cl::opt<bool> UseLoopVersioningLICM( 114 "enable-loop-versioning-licm", cl::init(false), cl::Hidden, 115 cl::desc("Enable the experimental Loop Versioning LICM pass")); 116 117 cl::opt<bool> 118 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, 119 cl::desc("Disable pre-instrumentation inliner")); 120 121 cl::opt<int> PreInlineThreshold( 122 "preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore, 123 cl::desc("Control the amount of inlining in pre-instrumentation inliner " 124 "(default = 75)")); 125 126 cl::opt<bool> 127 EnableGVNHoist("enable-gvn-hoist", cl::init(false), cl::ZeroOrMore, 128 cl::desc("Enable the GVN hoisting pass (default = off)")); 129 130 static cl::opt<bool> 131 DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false), 132 cl::Hidden, 133 cl::desc("Disable shrink-wrap library calls")); 134 135 static cl::opt<bool> EnableSimpleLoopUnswitch( 136 "enable-simple-loop-unswitch", cl::init(false), cl::Hidden, 137 cl::desc("Enable the simple loop unswitch pass. Also enables independent " 138 "cleanup passes integrated into the loop pass manager pipeline.")); 139 140 cl::opt<bool> 141 EnableGVNSink("enable-gvn-sink", cl::init(false), cl::ZeroOrMore, 142 cl::desc("Enable the GVN sinking pass (default = off)")); 143 144 // This option is used in simplifying testing SampleFDO optimizations for 145 // profile loading. 146 cl::opt<bool> 147 EnableCHR("enable-chr", cl::init(true), cl::Hidden, 148 cl::desc("Enable control height reduction optimization (CHR)")); 149 150 cl::opt<bool> FlattenedProfileUsed( 151 "flattened-profile-used", cl::init(false), cl::Hidden, 152 cl::desc("Indicate the sample profile being used is flattened, i.e., " 153 "no inline hierachy exists in the profile. ")); 154 155 cl::opt<bool> EnableOrderFileInstrumentation( 156 "enable-order-file-instrumentation", cl::init(false), cl::Hidden, 157 cl::desc("Enable order file instrumentation (default = off)")); 158 159 cl::opt<bool> EnableMatrix( 160 "enable-matrix", cl::init(false), cl::Hidden, 161 cl::desc("Enable lowering of the matrix intrinsics")); 162 163 cl::opt<bool> EnableConstraintElimination( 164 "enable-constraint-elimination", cl::init(false), cl::Hidden, 165 cl::desc( 166 "Enable pass to eliminate conditions based on linear constraints.")); 167 168 cl::opt<AttributorRunOption> AttributorRun( 169 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE), 170 cl::desc("Enable the attributor inter-procedural deduction pass."), 171 cl::values(clEnumValN(AttributorRunOption::ALL, "all", 172 "enable all attributor runs"), 173 clEnumValN(AttributorRunOption::MODULE, "module", 174 "enable module-wide attributor runs"), 175 clEnumValN(AttributorRunOption::CGSCC, "cgscc", 176 "enable call graph SCC attributor runs"), 177 clEnumValN(AttributorRunOption::NONE, "none", 178 "disable attributor runs"))); 179 180 extern cl::opt<bool> EnableKnowledgeRetention; 181 182 PassManagerBuilder::PassManagerBuilder() { 183 OptLevel = 2; 184 SizeLevel = 0; 185 LibraryInfo = nullptr; 186 Inliner = nullptr; 187 DisableUnrollLoops = false; 188 SLPVectorize = false; 189 LoopVectorize = true; 190 LoopsInterleaved = true; 191 RerollLoops = RunLoopRerolling; 192 NewGVN = RunNewGVN; 193 LicmMssaOptCap = SetLicmMssaOptCap; 194 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 195 DisableGVNLoadPRE = false; 196 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 197 VerifyInput = false; 198 VerifyOutput = false; 199 MergeFunctions = false; 200 PrepareForLTO = false; 201 EnablePGOInstrGen = false; 202 EnablePGOCSInstrGen = false; 203 EnablePGOCSInstrUse = false; 204 PGOInstrGen = ""; 205 PGOInstrUse = ""; 206 PGOSampleUse = ""; 207 PrepareForThinLTO = EnablePrepareForThinLTO; 208 PerformThinLTO = EnablePerformThinLTO; 209 DivergentTarget = false; 210 CallGraphProfile = true; 211 } 212 213 PassManagerBuilder::~PassManagerBuilder() { 214 delete LibraryInfo; 215 delete Inliner; 216 } 217 218 /// Set of global extensions, automatically added as part of the standard set. 219 static ManagedStatic< 220 SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy, 221 PassManagerBuilder::ExtensionFn, 222 PassManagerBuilder::GlobalExtensionID>, 223 8>> 224 GlobalExtensions; 225 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter; 226 227 /// Check if GlobalExtensions is constructed and not empty. 228 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger 229 /// the construction of the object. 230 static bool GlobalExtensionsNotEmpty() { 231 return GlobalExtensions.isConstructed() && !GlobalExtensions->empty(); 232 } 233 234 PassManagerBuilder::GlobalExtensionID 235 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty, 236 PassManagerBuilder::ExtensionFn Fn) { 237 auto ExtensionID = GlobalExtensionsCounter++; 238 GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID)); 239 return ExtensionID; 240 } 241 242 void PassManagerBuilder::removeGlobalExtension( 243 PassManagerBuilder::GlobalExtensionID ExtensionID) { 244 // RegisterStandardPasses may try to call this function after GlobalExtensions 245 // has already been destroyed; doing so should not generate an error. 246 if (!GlobalExtensions.isConstructed()) 247 return; 248 249 auto GlobalExtension = 250 llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) { 251 return std::get<2>(elem) == ExtensionID; 252 }); 253 assert(GlobalExtension != GlobalExtensions->end() && 254 "The extension ID to be removed should always be valid."); 255 256 GlobalExtensions->erase(GlobalExtension); 257 } 258 259 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { 260 Extensions.push_back(std::make_pair(Ty, std::move(Fn))); 261 } 262 263 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy, 264 legacy::PassManagerBase &PM) const { 265 if (GlobalExtensionsNotEmpty()) { 266 for (auto &Ext : *GlobalExtensions) { 267 if (std::get<0>(Ext) == ETy) 268 std::get<1>(Ext)(*this, PM); 269 } 270 } 271 for (unsigned i = 0, e = Extensions.size(); i != e; ++i) 272 if (Extensions[i].first == ETy) 273 Extensions[i].second(*this, PM); 274 } 275 276 void PassManagerBuilder::addInitialAliasAnalysisPasses( 277 legacy::PassManagerBase &PM) const { 278 switch (UseCFLAA) { 279 case ::CFLAAType::Steensgaard: 280 PM.add(createCFLSteensAAWrapperPass()); 281 break; 282 case ::CFLAAType::Andersen: 283 PM.add(createCFLAndersAAWrapperPass()); 284 break; 285 case ::CFLAAType::Both: 286 PM.add(createCFLSteensAAWrapperPass()); 287 PM.add(createCFLAndersAAWrapperPass()); 288 break; 289 default: 290 break; 291 } 292 293 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 294 // BasicAliasAnalysis wins if they disagree. This is intended to help 295 // support "obvious" type-punning idioms. 296 PM.add(createTypeBasedAAWrapperPass()); 297 PM.add(createScopedNoAliasAAWrapperPass()); 298 } 299 300 void PassManagerBuilder::populateFunctionPassManager( 301 legacy::FunctionPassManager &FPM) { 302 addExtensionsToPM(EP_EarlyAsPossible, FPM); 303 304 // Add LibraryInfo if we have some. 305 if (LibraryInfo) 306 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 307 308 // The backends do not handle matrix intrinsics currently. 309 // Make sure they are also lowered in O0. 310 // FIXME: A lightweight version of the pass should run in the backend 311 // pipeline on demand. 312 if (EnableMatrix && OptLevel == 0) 313 FPM.add(createLowerMatrixIntrinsicsMinimalPass()); 314 315 if (OptLevel == 0) return; 316 317 addInitialAliasAnalysisPasses(FPM); 318 319 // Lower llvm.expect to metadata before attempting transforms. 320 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 321 FPM.add(createLowerExpectIntrinsicPass()); 322 FPM.add(createCFGSimplificationPass()); 323 FPM.add(createSROAPass()); 324 FPM.add(createEarlyCSEPass()); 325 } 326 327 // Do PGO instrumentation generation or use pass as the option specified. 328 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM, 329 bool IsCS = false) { 330 if (IsCS) { 331 if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse) 332 return; 333 } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty()) 334 return; 335 336 // Perform the preinline and cleanup passes for O1 and above. 337 // We will not do this inline for context sensitive PGO (when IsCS is true). 338 if (OptLevel > 0 && !DisablePreInliner && PGOSampleUse.empty() && !IsCS) { 339 // Create preinline pass. We construct an InlineParams object and specify 340 // the threshold here to avoid the command line options of the regular 341 // inliner to influence pre-inlining. The only fields of InlineParams we 342 // care about are DefaultThreshold and HintThreshold. 343 InlineParams IP; 344 IP.DefaultThreshold = PreInlineThreshold; 345 // FIXME: The hint threshold has the same value used by the regular inliner 346 // when not optimzing for size. This should probably be lowered after 347 // performance testing. 348 // Use PreInlineThreshold for both -Os and -Oz. Not running preinliner makes 349 // the instrumented binary unusably large. Even if PreInlineThreshold is not 350 // correct thresold for -Oz, it is better than not running preinliner. 351 IP.HintThreshold = SizeLevel > 0 ? PreInlineThreshold : 325; 352 353 MPM.add(createFunctionInliningPass(IP)); 354 MPM.add(createSROAPass()); 355 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 356 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 357 MPM.add(createInstructionCombiningPass()); // Combine silly seq's 358 addExtensionsToPM(EP_Peephole, MPM); 359 } 360 if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) { 361 MPM.add(createPGOInstrumentationGenLegacyPass(IsCS)); 362 // Add the profile lowering pass. 363 InstrProfOptions Options; 364 if (!PGOInstrGen.empty()) 365 Options.InstrProfileOutput = PGOInstrGen; 366 Options.DoCounterPromotion = true; 367 Options.UseBFIInPromotion = IsCS; 368 MPM.add(createLoopRotatePass()); 369 MPM.add(createInstrProfilingLegacyPass(Options, IsCS)); 370 } 371 if (!PGOInstrUse.empty()) 372 MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS)); 373 // Indirect call promotion that promotes intra-module targets only. 374 // For ThinLTO this is done earlier due to interactions with globalopt 375 // for imported functions. We don't run this at -O0. 376 if (OptLevel > 0 && !IsCS) 377 MPM.add( 378 createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty())); 379 } 380 void PassManagerBuilder::addFunctionSimplificationPasses( 381 legacy::PassManagerBase &MPM) { 382 // Start of function pass. 383 // Break up aggregate allocas, using SSAUpdater. 384 assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!"); 385 MPM.add(createSROAPass()); 386 MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies 387 if (EnableKnowledgeRetention) 388 MPM.add(createAssumeSimplifyPass()); 389 390 if (OptLevel > 1) { 391 if (EnableGVNHoist) 392 MPM.add(createGVNHoistPass()); 393 if (EnableGVNSink) { 394 MPM.add(createGVNSinkPass()); 395 MPM.add(createCFGSimplificationPass()); 396 } 397 } 398 399 if (EnableConstraintElimination) 400 MPM.add(createConstraintEliminationPass()); 401 402 if (OptLevel > 1) { 403 // Speculative execution if the target has divergent branches; otherwise nop. 404 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass()); 405 406 MPM.add(createJumpThreadingPass()); // Thread jumps. 407 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 408 } 409 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 410 // Combine silly seq's 411 if (OptLevel > 2) 412 MPM.add(createAggressiveInstCombinerPass()); 413 MPM.add(createInstructionCombiningPass()); 414 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap) 415 MPM.add(createLibCallsShrinkWrapPass()); 416 addExtensionsToPM(EP_Peephole, MPM); 417 418 // Optimize memory intrinsic calls based on the profiled size information. 419 if (SizeLevel == 0) 420 MPM.add(createPGOMemOPSizeOptLegacyPass()); 421 422 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 423 if (OptLevel > 1) 424 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 425 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 426 MPM.add(createReassociatePass()); // Reassociate expressions 427 428 // Begin the loop pass pipeline. 429 if (EnableSimpleLoopUnswitch) { 430 // The simple loop unswitch pass relies on separate cleanup passes. Schedule 431 // them first so when we re-process a loop they run before other loop 432 // passes. 433 MPM.add(createLoopInstSimplifyPass()); 434 MPM.add(createLoopSimplifyCFGPass()); 435 } 436 // Try to remove as much code from the loop header as possible, 437 // to reduce amount of IR that will have to be duplicated. 438 // TODO: Investigate promotion cap for O1. 439 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 440 // Rotate Loop - disable header duplication at -Oz 441 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 442 // TODO: Investigate promotion cap for O1. 443 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 444 if (EnableSimpleLoopUnswitch) 445 MPM.add(createSimpleLoopUnswitchLegacyPass()); 446 else 447 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 448 // FIXME: We break the loop pass pipeline here in order to do full 449 // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the 450 // need for this. 451 MPM.add(createCFGSimplificationPass()); 452 MPM.add(createInstructionCombiningPass()); 453 // We resume loop passes creating a second loop pipeline here. 454 if (EnableLoopFlatten) { 455 MPM.add(createLoopFlattenPass()); // Flatten loops 456 MPM.add(createLoopSimplifyCFGPass()); 457 } 458 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 459 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 460 addExtensionsToPM(EP_LateLoopOptimizations, MPM); 461 MPM.add(createLoopDeletionPass()); // Delete dead loops 462 463 if (EnableLoopInterchange) 464 MPM.add(createLoopInterchangePass()); // Interchange loops 465 466 // Unroll small loops and perform peeling. 467 MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 468 ForgetAllSCEVInLoopUnroll)); 469 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 470 // This ends the loop pass pipelines. 471 472 // Break up allocas that may now be splittable after loop unrolling. 473 MPM.add(createSROAPass()); 474 475 if (OptLevel > 1) { 476 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 477 MPM.add(NewGVN ? createNewGVNPass() 478 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 479 } 480 MPM.add(createSCCPPass()); // Constant prop with SCCP 481 482 if (EnableConstraintElimination) 483 MPM.add(createConstraintEliminationPass()); 484 485 // Delete dead bit computations (instcombine runs after to fold away the dead 486 // computations, and then ADCE will run later to exploit any new DCE 487 // opportunities that creates). 488 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 489 490 // Run instcombine after redundancy elimination to exploit opportunities 491 // opened up by them. 492 MPM.add(createInstructionCombiningPass()); 493 addExtensionsToPM(EP_Peephole, MPM); 494 if (OptLevel > 1) { 495 MPM.add(createJumpThreadingPass()); // Thread jumps 496 MPM.add(createCorrelatedValuePropagationPass()); 497 } 498 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 499 500 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 501 // TODO: Investigate if this is too expensive at O1. 502 if (OptLevel > 1) { 503 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 504 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 505 } 506 507 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 508 509 if (RerollLoops) 510 MPM.add(createLoopRerollPass()); 511 512 // Merge & remove BBs and sink & hoist common instructions. 513 MPM.add(createCFGSimplificationPass( 514 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true))); 515 // Clean up after everything. 516 MPM.add(createInstructionCombiningPass()); 517 addExtensionsToPM(EP_Peephole, MPM); 518 519 if (EnableCHR && OptLevel >= 3 && 520 (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen)) 521 MPM.add(createControlHeightReductionLegacyPass()); 522 } 523 524 /// FIXME: Should LTO cause any differences to this set of passes? 525 void PassManagerBuilder::addVectorPasses(legacy::PassManagerBase &PM, 526 bool IsLTO) { 527 PM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize)); 528 529 if (IsLTO) { 530 // The vectorizer may have significantly shortened a loop body; unroll 531 // again. Unroll small loops to hide loop backedge latency and saturate any 532 // parallel execution resources of an out-of-order processor. We also then 533 // need to clean up redundancies and loop invariant code. 534 // FIXME: It would be really good to use a loop-integrated instruction 535 // combiner for cleanup here so that the unrolling and LICM can be pipelined 536 // across the loop nests. 537 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 538 if (EnableUnrollAndJam && !DisableUnrollLoops) 539 PM.add(createLoopUnrollAndJamPass(OptLevel)); 540 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 541 ForgetAllSCEVInLoopUnroll)); 542 PM.add(createWarnMissedTransformationsPass()); 543 } 544 545 if (!IsLTO) { 546 // Eliminate loads by forwarding stores from the previous iteration to loads 547 // of the current iteration. 548 PM.add(createLoopLoadEliminationPass()); 549 } 550 // Cleanup after the loop optimization passes. 551 PM.add(createInstructionCombiningPass()); 552 553 if (OptLevel > 1 && ExtraVectorizerPasses) { 554 // At higher optimization levels, try to clean up any runtime overlap and 555 // alignment checks inserted by the vectorizer. We want to track correlated 556 // runtime checks for two inner loops in the same outer loop, fold any 557 // common computations, hoist loop-invariant aspects out of any outer loop, 558 // and unswitch the runtime checks if possible. Once hoisted, we may have 559 // dead (or speculatable) control flows or more combining opportunities. 560 PM.add(createEarlyCSEPass()); 561 PM.add(createCorrelatedValuePropagationPass()); 562 PM.add(createInstructionCombiningPass()); 563 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 564 PM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 565 PM.add(createCFGSimplificationPass()); 566 PM.add(createInstructionCombiningPass()); 567 } 568 569 // Now that we've formed fast to execute loop structures, we do further 570 // optimizations. These are run afterward as they might block doing complex 571 // analyses and transforms such as what are needed for loop vectorization. 572 573 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 574 // GVN, loop transforms, and others have already run, so it's now better to 575 // convert to more optimized IR using more aggressive simplify CFG options. 576 // The extra sinking transform can create larger basic blocks, so do this 577 // before SLP vectorization. 578 PM.add(createCFGSimplificationPass(SimplifyCFGOptions() 579 .forwardSwitchCondToPhi(true) 580 .convertSwitchToLookupTable(true) 581 .needCanonicalLoops(false) 582 .hoistCommonInsts(true) 583 .sinkCommonInsts(true))); 584 585 if (IsLTO) { 586 PM.add(createSCCPPass()); // Propagate exposed constants 587 PM.add(createInstructionCombiningPass()); // Clean up again 588 PM.add(createBitTrackingDCEPass()); 589 } 590 591 // Optimize parallel scalar instruction chains into SIMD instructions. 592 if (SLPVectorize) { 593 PM.add(createSLPVectorizerPass()); 594 if (OptLevel > 1 && ExtraVectorizerPasses) 595 PM.add(createEarlyCSEPass()); 596 } 597 598 // Enhance/cleanup vector code. 599 PM.add(createVectorCombinePass()); 600 601 if (IsLTO) { 602 // After vectorization, assume intrinsics may tell us more about pointer 603 // alignments. 604 PM.add(createAlignmentFromAssumptionsPass()); 605 } 606 addExtensionsToPM(EP_Peephole, PM); 607 PM.add(createInstructionCombiningPass()); 608 609 if (!IsLTO) { 610 // The vectorizer may have significantly shortened a loop body; unroll 611 // again. Unroll small loops to hide loop backedge latency and saturate any 612 // parallel execution resources of an out-of-order processor. We also then 613 // need to clean up redundancies and loop invariant code. 614 // FIXME: It would be really good to use a loop-integrated instruction 615 // combiner for cleanup here so that the unrolling and LICM can be pipelined 616 // across the loop nests. 617 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 618 if (EnableUnrollAndJam && !DisableUnrollLoops) 619 PM.add(createLoopUnrollAndJamPass(OptLevel)); 620 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 621 ForgetAllSCEVInLoopUnroll)); 622 if (!DisableUnrollLoops) 623 PM.add(createInstructionCombiningPass()); 624 } 625 } 626 627 void PassManagerBuilder::populateModulePassManager( 628 legacy::PassManagerBase &MPM) { 629 // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link 630 // is handled separately, so just check this is not the ThinLTO post-link. 631 bool DefaultOrPreLinkPipeline = !PerformThinLTO; 632 633 MPM.add(createAnnotation2MetadataLegacyPass()); 634 635 if (!PGOSampleUse.empty()) { 636 MPM.add(createPruneEHPass()); 637 // In ThinLTO mode, when flattened profile is used, all the available 638 // profile information will be annotated in PreLink phase so there is 639 // no need to load the profile again in PostLink. 640 if (!(FlattenedProfileUsed && PerformThinLTO)) 641 MPM.add(createSampleProfileLoaderPass(PGOSampleUse)); 642 } 643 644 // Allow forcing function attributes as a debugging and tuning aid. 645 MPM.add(createForceFunctionAttrsLegacyPass()); 646 647 // If all optimizations are disabled, just run the always-inline pass and, 648 // if enabled, the function merging pass. 649 if (OptLevel == 0) { 650 addPGOInstrPasses(MPM); 651 if (Inliner) { 652 MPM.add(Inliner); 653 Inliner = nullptr; 654 } 655 656 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 657 // creates a CGSCC pass manager, but we don't want to add extensions into 658 // that pass manager. To prevent this we insert a no-op module pass to reset 659 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 660 // builds. The function merging pass is 661 if (MergeFunctions) 662 MPM.add(createMergeFunctionsPass()); 663 else if (GlobalExtensionsNotEmpty() || !Extensions.empty()) 664 MPM.add(createBarrierNoopPass()); 665 666 if (PerformThinLTO) { 667 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 668 // Drop available_externally and unreferenced globals. This is necessary 669 // with ThinLTO in order to avoid leaving undefined references to dead 670 // globals in the object file. 671 MPM.add(createEliminateAvailableExternallyPass()); 672 MPM.add(createGlobalDCEPass()); 673 } 674 675 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 676 677 if (PrepareForLTO || PrepareForThinLTO) { 678 MPM.add(createCanonicalizeAliasesPass()); 679 // Rename anon globals to be able to export them in the summary. 680 // This has to be done after we add the extensions to the pass manager 681 // as there could be passes (e.g. Adddress sanitizer) which introduce 682 // new unnamed globals. 683 MPM.add(createNameAnonGlobalPass()); 684 } 685 686 MPM.add(createAnnotationRemarksLegacyPass()); 687 return; 688 } 689 690 // Add LibraryInfo if we have some. 691 if (LibraryInfo) 692 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 693 694 addInitialAliasAnalysisPasses(MPM); 695 696 // For ThinLTO there are two passes of indirect call promotion. The 697 // first is during the compile phase when PerformThinLTO=false and 698 // intra-module indirect call targets are promoted. The second is during 699 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 700 // inter-module indirect calls. For that we perform indirect call promotion 701 // earlier in the pass pipeline, here before globalopt. Otherwise imported 702 // available_externally functions look unreferenced and are removed. 703 if (PerformThinLTO) { 704 MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true, 705 !PGOSampleUse.empty())); 706 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 707 } 708 709 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops 710 // as it will change the CFG too much to make the 2nd profile annotation 711 // in backend more difficult. 712 bool PrepareForThinLTOUsingPGOSampleProfile = 713 PrepareForThinLTO && !PGOSampleUse.empty(); 714 if (PrepareForThinLTOUsingPGOSampleProfile) 715 DisableUnrollLoops = true; 716 717 // Infer attributes about declarations if possible. 718 MPM.add(createInferFunctionAttrsLegacyPass()); 719 720 // Infer attributes on declarations, call sites, arguments, etc. 721 if (AttributorRun & AttributorRunOption::MODULE) 722 MPM.add(createAttributorLegacyPass()); 723 724 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 725 726 if (OptLevel > 2) 727 MPM.add(createCallSiteSplittingPass()); 728 729 MPM.add(createIPSCCPPass()); // IP SCCP 730 MPM.add(createCalledValuePropagationPass()); 731 732 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 733 // Promote any localized global vars. 734 MPM.add(createPromoteMemoryToRegisterPass()); 735 736 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 737 738 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE 739 addExtensionsToPM(EP_Peephole, MPM); 740 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE 741 742 // For SamplePGO in ThinLTO compile phase, we do not want to do indirect 743 // call promotion as it will change the CFG too much to make the 2nd 744 // profile annotation in backend more difficult. 745 // PGO instrumentation is added during the compile phase for ThinLTO, do 746 // not run it a second time 747 if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile) 748 addPGOInstrPasses(MPM); 749 750 // Create profile COMDAT variables. Lld linker wants to see all variables 751 // before the LTO/ThinLTO link since it needs to resolve symbols/comdats. 752 if (!PerformThinLTO && EnablePGOCSInstrGen) 753 MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen)); 754 755 // We add a module alias analysis pass here. In part due to bugs in the 756 // analysis infrastructure this "works" in that the analysis stays alive 757 // for the entire SCC pass run below. 758 MPM.add(createGlobalsAAWrapperPass()); 759 760 // Start of CallGraph SCC passes. 761 MPM.add(createPruneEHPass()); // Remove dead EH info 762 bool RunInliner = false; 763 if (Inliner) { 764 MPM.add(Inliner); 765 Inliner = nullptr; 766 RunInliner = true; 767 } 768 769 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 770 if (AttributorRun & AttributorRunOption::CGSCC) 771 MPM.add(createAttributorCGSCCLegacyPass()); 772 773 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 774 // there are no OpenMP runtime calls present in the module. 775 if (OptLevel > 1) 776 MPM.add(createOpenMPOptCGSCCLegacyPass()); 777 778 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 779 if (OptLevel > 2) 780 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 781 782 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 783 addFunctionSimplificationPasses(MPM); 784 785 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 786 // pass manager that we are specifically trying to avoid. To prevent this 787 // we must insert a no-op module pass to reset the pass manager. 788 MPM.add(createBarrierNoopPass()); 789 790 if (RunPartialInlining) 791 MPM.add(createPartialInliningPass()); 792 793 if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO) 794 // Remove avail extern fns and globals definitions if we aren't 795 // compiling an object file for later LTO. For LTO we want to preserve 796 // these so they are eligible for inlining at link-time. Note if they 797 // are unreferenced they will be removed by GlobalDCE later, so 798 // this only impacts referenced available externally globals. 799 // Eventually they will be suppressed during codegen, but eliminating 800 // here enables more opportunity for GlobalDCE as it may make 801 // globals referenced by available external functions dead 802 // and saves running remaining passes on the eliminated functions. 803 MPM.add(createEliminateAvailableExternallyPass()); 804 805 // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass 806 // for LTO and ThinLTO -- The actual pass will be called after all inlines 807 // are performed. 808 // Need to do this after COMDAT variables have been eliminated, 809 // (i.e. after EliminateAvailableExternallyPass). 810 if (!(PrepareForLTO || PrepareForThinLTO)) 811 addPGOInstrPasses(MPM, /* IsCS */ true); 812 813 if (EnableOrderFileInstrumentation) 814 MPM.add(createInstrOrderFilePass()); 815 816 MPM.add(createReversePostOrderFunctionAttrsPass()); 817 818 // The inliner performs some kind of dead code elimination as it goes, 819 // but there are cases that are not really caught by it. We might 820 // at some point consider teaching the inliner about them, but it 821 // is OK for now to run GlobalOpt + GlobalDCE in tandem as their 822 // benefits generally outweight the cost, making the whole pipeline 823 // faster. 824 if (RunInliner) { 825 MPM.add(createGlobalOptimizerPass()); 826 MPM.add(createGlobalDCEPass()); 827 } 828 829 // If we are planning to perform ThinLTO later, let's not bloat the code with 830 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 831 // during ThinLTO and perform the rest of the optimizations afterward. 832 if (PrepareForThinLTO) { 833 // Ensure we perform any last passes, but do so before renaming anonymous 834 // globals in case the passes add any. 835 addExtensionsToPM(EP_OptimizerLast, MPM); 836 MPM.add(createCanonicalizeAliasesPass()); 837 // Rename anon globals to be able to export them in the summary. 838 MPM.add(createNameAnonGlobalPass()); 839 return; 840 } 841 842 if (PerformThinLTO) 843 // Optimize globals now when performing ThinLTO, this enables more 844 // optimizations later. 845 MPM.add(createGlobalOptimizerPass()); 846 847 // Scheduling LoopVersioningLICM when inlining is over, because after that 848 // we may see more accurate aliasing. Reason to run this late is that too 849 // early versioning may prevent further inlining due to increase of code 850 // size. By placing it just after inlining other optimizations which runs 851 // later might get benefit of no-alias assumption in clone loop. 852 if (UseLoopVersioningLICM) { 853 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 854 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 855 } 856 857 // We add a fresh GlobalsModRef run at this point. This is particularly 858 // useful as the above will have inlined, DCE'ed, and function-attr 859 // propagated everything. We should at this point have a reasonably minimal 860 // and richly annotated call graph. By computing aliasing and mod/ref 861 // information for all local globals here, the late loop passes and notably 862 // the vectorizer will be able to use them to help recognize vectorizable 863 // memory operations. 864 // 865 // Note that this relies on a bug in the pass manager which preserves 866 // a module analysis into a function pass pipeline (and throughout it) so 867 // long as the first function pass doesn't invalidate the module analysis. 868 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 869 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 870 // (doing nothing preserves it as it is required to be conservatively 871 // correct in the face of IR changes). 872 MPM.add(createGlobalsAAWrapperPass()); 873 874 MPM.add(createFloat2IntPass()); 875 MPM.add(createLowerConstantIntrinsicsPass()); 876 877 if (EnableMatrix) { 878 MPM.add(createLowerMatrixIntrinsicsPass()); 879 // CSE the pointer arithmetic of the column vectors. This allows alias 880 // analysis to establish no-aliasing between loads and stores of different 881 // columns of the same matrix. 882 MPM.add(createEarlyCSEPass(false)); 883 } 884 885 addExtensionsToPM(EP_VectorizerStart, MPM); 886 887 // Re-rotate loops in all our loop nests. These may have fallout out of 888 // rotated form due to GVN or other transformations, and the vectorizer relies 889 // on the rotated form. Disable header duplication at -Oz. 890 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 891 892 // Distribute loops to allow partial vectorization. I.e. isolate dependences 893 // into separate loop that would otherwise inhibit vectorization. This is 894 // currently only performed for loops marked with the metadata 895 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 896 MPM.add(createLoopDistributePass()); 897 898 addVectorPasses(MPM, /* IsLTO */ false); 899 900 if (!DisableUnrollLoops) { 901 // Runtime unrolling will introduce runtime check in loop prologue. If the 902 // unrolled loop is a inner loop, then the prologue will be inside the 903 // outer loop. LICM pass can help to promote the runtime check out if the 904 // checked value is loop invariant. 905 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 906 } 907 908 MPM.add(createWarnMissedTransformationsPass()); 909 910 // After vectorization and unrolling, assume intrinsics may tell us more 911 // about pointer alignments. 912 MPM.add(createAlignmentFromAssumptionsPass()); 913 914 // FIXME: We shouldn't bother with this anymore. 915 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 916 917 // GlobalOpt already deletes dead functions and globals, at -O2 try a 918 // late pass of GlobalDCE. It is capable of deleting dead cycles. 919 if (OptLevel > 1) { 920 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 921 MPM.add(createConstantMergePass()); // Merge dup global constants 922 } 923 924 // See comment in the new PM for justification of scheduling splitting at 925 // this stage (\ref buildModuleSimplificationPipeline). 926 if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO)) 927 MPM.add(createHotColdSplittingPass()); 928 929 if (EnableIROutliner) 930 MPM.add(createIROutlinerPass()); 931 932 if (MergeFunctions) 933 MPM.add(createMergeFunctionsPass()); 934 935 // Add Module flag "CG Profile" based on Branch Frequency Information. 936 if (CallGraphProfile) 937 MPM.add(createCGProfileLegacyPass()); 938 939 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 940 // canonicalization pass that enables other optimizations. As a result, 941 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 942 // result too early. 943 MPM.add(createLoopSinkPass()); 944 // Get rid of LCSSA nodes. 945 MPM.add(createInstSimplifyLegacyPass()); 946 947 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 948 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 949 // flattening of blocks. 950 MPM.add(createDivRemPairsPass()); 951 952 // LoopSink (and other loop passes since the last simplifyCFG) might have 953 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 954 MPM.add(createCFGSimplificationPass()); 955 956 addExtensionsToPM(EP_OptimizerLast, MPM); 957 958 if (PrepareForLTO) { 959 MPM.add(createCanonicalizeAliasesPass()); 960 // Rename anon globals to be able to handle them in the summary 961 MPM.add(createNameAnonGlobalPass()); 962 } 963 964 MPM.add(createAnnotationRemarksLegacyPass()); 965 } 966 967 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 968 // Load sample profile before running the LTO optimization pipeline. 969 if (!PGOSampleUse.empty()) { 970 PM.add(createPruneEHPass()); 971 PM.add(createSampleProfileLoaderPass(PGOSampleUse)); 972 } 973 974 // Remove unused virtual tables to improve the quality of code generated by 975 // whole-program devirtualization and bitset lowering. 976 PM.add(createGlobalDCEPass()); 977 978 // Provide AliasAnalysis services for optimizations. 979 addInitialAliasAnalysisPasses(PM); 980 981 // Allow forcing function attributes as a debugging and tuning aid. 982 PM.add(createForceFunctionAttrsLegacyPass()); 983 984 // Infer attributes about declarations if possible. 985 PM.add(createInferFunctionAttrsLegacyPass()); 986 987 if (OptLevel > 1) { 988 // Split call-site with more constrained arguments. 989 PM.add(createCallSiteSplittingPass()); 990 991 // Indirect call promotion. This should promote all the targets that are 992 // left by the earlier promotion pass that promotes intra-module targets. 993 // This two-step promotion is to save the compile time. For LTO, it should 994 // produce the same result as if we only do promotion here. 995 PM.add( 996 createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty())); 997 998 // Propagate constants at call sites into the functions they call. This 999 // opens opportunities for globalopt (and inlining) by substituting function 1000 // pointers passed as arguments to direct uses of functions. 1001 PM.add(createIPSCCPPass()); 1002 1003 // Attach metadata to indirect call sites indicating the set of functions 1004 // they may target at run-time. This should follow IPSCCP. 1005 PM.add(createCalledValuePropagationPass()); 1006 1007 // Infer attributes on declarations, call sites, arguments, etc. 1008 if (AttributorRun & AttributorRunOption::MODULE) 1009 PM.add(createAttributorLegacyPass()); 1010 } 1011 1012 // Infer attributes about definitions. The readnone attribute in particular is 1013 // required for virtual constant propagation. 1014 PM.add(createPostOrderFunctionAttrsLegacyPass()); 1015 PM.add(createReversePostOrderFunctionAttrsPass()); 1016 1017 // Split globals using inrange annotations on GEP indices. This can help 1018 // improve the quality of generated code when virtual constant propagation or 1019 // control flow integrity are enabled. 1020 PM.add(createGlobalSplitPass()); 1021 1022 // Apply whole-program devirtualization and virtual constant propagation. 1023 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 1024 1025 // That's all we need at opt level 1. 1026 if (OptLevel == 1) 1027 return; 1028 1029 // Now that we internalized some globals, see if we can hack on them! 1030 PM.add(createGlobalOptimizerPass()); 1031 // Promote any localized global vars. 1032 PM.add(createPromoteMemoryToRegisterPass()); 1033 1034 // Linking modules together can lead to duplicated global constants, only 1035 // keep one copy of each constant. 1036 PM.add(createConstantMergePass()); 1037 1038 // Remove unused arguments from functions. 1039 PM.add(createDeadArgEliminationPass()); 1040 1041 // Reduce the code after globalopt and ipsccp. Both can open up significant 1042 // simplification opportunities, and both can propagate functions through 1043 // function pointers. When this happens, we often have to resolve varargs 1044 // calls, etc, so let instcombine do this. 1045 if (OptLevel > 2) 1046 PM.add(createAggressiveInstCombinerPass()); 1047 PM.add(createInstructionCombiningPass()); 1048 addExtensionsToPM(EP_Peephole, PM); 1049 1050 // Inline small functions 1051 bool RunInliner = Inliner; 1052 if (RunInliner) { 1053 PM.add(Inliner); 1054 Inliner = nullptr; 1055 } 1056 1057 PM.add(createPruneEHPass()); // Remove dead EH info. 1058 1059 // CSFDO instrumentation and use pass. 1060 addPGOInstrPasses(PM, /* IsCS */ true); 1061 1062 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 1063 if (AttributorRun & AttributorRunOption::CGSCC) 1064 PM.add(createAttributorCGSCCLegacyPass()); 1065 1066 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 1067 // there are no OpenMP runtime calls present in the module. 1068 if (OptLevel > 1) 1069 PM.add(createOpenMPOptCGSCCLegacyPass()); 1070 1071 // Optimize globals again if we ran the inliner. 1072 if (RunInliner) 1073 PM.add(createGlobalOptimizerPass()); 1074 PM.add(createGlobalDCEPass()); // Remove dead functions. 1075 1076 // If we didn't decide to inline a function, check to see if we can 1077 // transform it to pass arguments by value instead of by reference. 1078 PM.add(createArgumentPromotionPass()); 1079 1080 // The IPO passes may leave cruft around. Clean up after them. 1081 PM.add(createInstructionCombiningPass()); 1082 addExtensionsToPM(EP_Peephole, PM); 1083 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1084 1085 // Break up allocas 1086 PM.add(createSROAPass()); 1087 1088 // LTO provides additional opportunities for tailcall elimination due to 1089 // link-time inlining, and visibility of nocapture attribute. 1090 if (OptLevel > 1) 1091 PM.add(createTailCallEliminationPass()); 1092 1093 // Infer attributes on declarations, call sites, arguments, etc. 1094 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 1095 // Run a few AA driven optimizations here and now, to cleanup the code. 1096 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 1097 1098 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 1099 PM.add(NewGVN ? createNewGVNPass() 1100 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 1101 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 1102 1103 // Nuke dead stores. 1104 PM.add(createDeadStoreEliminationPass()); 1105 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 1106 1107 // More loops are countable; try to optimize them. 1108 if (EnableLoopFlatten) 1109 PM.add(createLoopFlattenPass()); 1110 PM.add(createIndVarSimplifyPass()); 1111 PM.add(createLoopDeletionPass()); 1112 if (EnableLoopInterchange) 1113 PM.add(createLoopInterchangePass()); 1114 1115 if (EnableConstraintElimination) 1116 PM.add(createConstraintEliminationPass()); 1117 1118 // Unroll small loops and perform peeling. 1119 PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 1120 ForgetAllSCEVInLoopUnroll)); 1121 PM.add(createLoopDistributePass()); 1122 1123 addVectorPasses(PM, /* IsLTO */ true); 1124 1125 addExtensionsToPM(EP_Peephole, PM); 1126 1127 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1128 } 1129 1130 void PassManagerBuilder::addLateLTOOptimizationPasses( 1131 legacy::PassManagerBase &PM) { 1132 // See comment in the new PM for justification of scheduling splitting at 1133 // this stage (\ref buildLTODefaultPipeline). 1134 if (EnableHotColdSplit) 1135 PM.add(createHotColdSplittingPass()); 1136 1137 // Delete basic blocks, which optimization passes may have killed. 1138 PM.add( 1139 createCFGSimplificationPass(SimplifyCFGOptions().hoistCommonInsts(true))); 1140 1141 // Drop bodies of available externally objects to improve GlobalDCE. 1142 PM.add(createEliminateAvailableExternallyPass()); 1143 1144 // Now that we have optimized the program, discard unreachable functions. 1145 PM.add(createGlobalDCEPass()); 1146 1147 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 1148 // currently it damages debug info. 1149 if (MergeFunctions) 1150 PM.add(createMergeFunctionsPass()); 1151 } 1152 1153 void PassManagerBuilder::populateThinLTOPassManager( 1154 legacy::PassManagerBase &PM) { 1155 PerformThinLTO = true; 1156 if (LibraryInfo) 1157 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1158 1159 if (VerifyInput) 1160 PM.add(createVerifierPass()); 1161 1162 if (ImportSummary) { 1163 // This pass imports type identifier resolutions for whole-program 1164 // devirtualization and CFI. It must run early because other passes may 1165 // disturb the specific instruction patterns that these passes look for, 1166 // creating dependencies on resolutions that may not appear in the summary. 1167 // 1168 // For example, GVN may transform the pattern assume(type.test) appearing in 1169 // two basic blocks into assume(phi(type.test, type.test)), which would 1170 // transform a dependency on a WPD resolution into a dependency on a type 1171 // identifier resolution for CFI. 1172 // 1173 // Also, WPD has access to more precise information than ICP and can 1174 // devirtualize more effectively, so it should operate on the IR first. 1175 PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary)); 1176 PM.add(createLowerTypeTestsPass(nullptr, ImportSummary)); 1177 } 1178 1179 populateModulePassManager(PM); 1180 1181 if (VerifyOutput) 1182 PM.add(createVerifierPass()); 1183 PerformThinLTO = false; 1184 } 1185 1186 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) { 1187 if (LibraryInfo) 1188 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1189 1190 if (VerifyInput) 1191 PM.add(createVerifierPass()); 1192 1193 addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM); 1194 1195 if (OptLevel != 0) 1196 addLTOOptimizationPasses(PM); 1197 else { 1198 // The whole-program-devirt pass needs to run at -O0 because only it knows 1199 // about the llvm.type.checked.load intrinsic: it needs to both lower the 1200 // intrinsic itself and handle it in the summary. 1201 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 1202 } 1203 1204 // Create a function that performs CFI checks for cross-DSO calls with targets 1205 // in the current module. 1206 PM.add(createCrossDSOCFIPass()); 1207 1208 // Lower type metadata and the type.test intrinsic. This pass supports Clang's 1209 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at 1210 // link time if CFI is enabled. The pass does nothing if CFI is disabled. 1211 PM.add(createLowerTypeTestsPass(ExportSummary, nullptr)); 1212 // Run a second time to clean up any type tests left behind by WPD for use 1213 // in ICP (which is performed earlier than this in the regular LTO pipeline). 1214 PM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 1215 1216 if (OptLevel != 0) 1217 addLateLTOOptimizationPasses(PM); 1218 1219 addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM); 1220 1221 PM.add(createAnnotationRemarksLegacyPass()); 1222 1223 if (VerifyOutput) 1224 PM.add(createVerifierPass()); 1225 } 1226 1227 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 1228 PassManagerBuilder *PMB = new PassManagerBuilder(); 1229 return wrap(PMB); 1230 } 1231 1232 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 1233 PassManagerBuilder *Builder = unwrap(PMB); 1234 delete Builder; 1235 } 1236 1237 void 1238 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 1239 unsigned OptLevel) { 1240 PassManagerBuilder *Builder = unwrap(PMB); 1241 Builder->OptLevel = OptLevel; 1242 } 1243 1244 void 1245 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 1246 unsigned SizeLevel) { 1247 PassManagerBuilder *Builder = unwrap(PMB); 1248 Builder->SizeLevel = SizeLevel; 1249 } 1250 1251 void 1252 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 1253 LLVMBool Value) { 1254 // NOTE: The DisableUnitAtATime switch has been removed. 1255 } 1256 1257 void 1258 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 1259 LLVMBool Value) { 1260 PassManagerBuilder *Builder = unwrap(PMB); 1261 Builder->DisableUnrollLoops = Value; 1262 } 1263 1264 void 1265 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 1266 LLVMBool Value) { 1267 // NOTE: The simplify-libcalls pass has been removed. 1268 } 1269 1270 void 1271 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 1272 unsigned Threshold) { 1273 PassManagerBuilder *Builder = unwrap(PMB); 1274 Builder->Inliner = createFunctionInliningPass(Threshold); 1275 } 1276 1277 void 1278 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 1279 LLVMPassManagerRef PM) { 1280 PassManagerBuilder *Builder = unwrap(PMB); 1281 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 1282 Builder->populateFunctionPassManager(*FPM); 1283 } 1284 1285 void 1286 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 1287 LLVMPassManagerRef PM) { 1288 PassManagerBuilder *Builder = unwrap(PMB); 1289 legacy::PassManagerBase *MPM = unwrap(PM); 1290 Builder->populateModulePassManager(*MPM); 1291 } 1292 1293 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 1294 LLVMPassManagerRef PM, 1295 LLVMBool Internalize, 1296 LLVMBool RunInliner) { 1297 PassManagerBuilder *Builder = unwrap(PMB); 1298 legacy::PassManagerBase *LPM = unwrap(PM); 1299 1300 // A small backwards compatibility hack. populateLTOPassManager used to take 1301 // an RunInliner option. 1302 if (RunInliner && !Builder->Inliner) 1303 Builder->Inliner = createFunctionInliningPass(); 1304 1305 Builder->populateLTOPassManager(*LPM); 1306 } 1307