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