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/CFLAndersAliasAnalysis.h" 19 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/ScopedNoAliasAA.h" 22 #include "llvm/Analysis/TargetLibraryInfo.h" 23 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 24 #include "llvm/IR/LegacyPassManager.h" 25 #include "llvm/Support/CommandLine.h" 26 #include "llvm/Support/ManagedStatic.h" 27 #include "llvm/Target/CGPassBuilderOption.h" 28 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 29 #include "llvm/Transforms/IPO.h" 30 #include "llvm/Transforms/IPO/Attributor.h" 31 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 32 #include "llvm/Transforms/IPO/FunctionAttrs.h" 33 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 34 #include "llvm/Transforms/InstCombine/InstCombine.h" 35 #include "llvm/Transforms/Instrumentation.h" 36 #include "llvm/Transforms/Scalar.h" 37 #include "llvm/Transforms/Scalar/GVN.h" 38 #include "llvm/Transforms/Scalar/LICM.h" 39 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 40 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 41 #include "llvm/Transforms/Utils.h" 42 #include "llvm/Transforms/Vectorize.h" 43 44 using namespace llvm; 45 46 namespace llvm { 47 cl::opt<bool> RunPartialInlining("enable-partial-inlining", cl::Hidden, 48 cl::desc("Run Partial inlinining pass")); 49 50 static cl::opt<bool> 51 UseGVNAfterVectorization("use-gvn-after-vectorization", 52 cl::init(false), cl::Hidden, 53 cl::desc("Run GVN instead of Early CSE after vectorization passes")); 54 55 cl::opt<bool> ExtraVectorizerPasses( 56 "extra-vectorizer-passes", cl::init(false), cl::Hidden, 57 cl::desc("Run cleanup optimization passes after vectorization.")); 58 59 static cl::opt<bool> 60 RunLoopRerolling("reroll-loops", cl::Hidden, 61 cl::desc("Run the loop rerolling pass")); 62 63 cl::opt<bool> RunNewGVN("enable-newgvn", cl::init(false), cl::Hidden, 64 cl::desc("Run the NewGVN pass")); 65 66 // Experimental option to use CFL-AA 67 static cl::opt<::CFLAAType> 68 UseCFLAA("use-cfl-aa", cl::init(::CFLAAType::None), cl::Hidden, 69 cl::desc("Enable the new, experimental CFL alias analysis"), 70 cl::values(clEnumValN(::CFLAAType::None, "none", "Disable CFL-AA"), 71 clEnumValN(::CFLAAType::Steensgaard, "steens", 72 "Enable unification-based CFL-AA"), 73 clEnumValN(::CFLAAType::Andersen, "anders", 74 "Enable inclusion-based CFL-AA"), 75 clEnumValN(::CFLAAType::Both, "both", 76 "Enable both variants of CFL-AA"))); 77 78 cl::opt<bool> EnableLoopInterchange( 79 "enable-loopinterchange", cl::init(false), cl::Hidden, 80 cl::desc("Enable the experimental LoopInterchange Pass")); 81 82 cl::opt<bool> EnableUnrollAndJam("enable-unroll-and-jam", cl::init(false), 83 cl::Hidden, 84 cl::desc("Enable Unroll And Jam Pass")); 85 86 cl::opt<bool> EnableLoopFlatten("enable-loop-flatten", cl::init(false), 87 cl::Hidden, 88 cl::desc("Enable the LoopFlatten Pass")); 89 90 cl::opt<bool> EnableDFAJumpThreading("enable-dfa-jump-thread", 91 cl::desc("Enable DFA jump threading."), 92 cl::init(false), cl::Hidden); 93 94 static cl::opt<bool> 95 EnablePrepareForThinLTO("prepare-for-thinlto", cl::init(false), cl::Hidden, 96 cl::desc("Enable preparation for ThinLTO.")); 97 98 static cl::opt<bool> 99 EnablePerformThinLTO("perform-thinlto", cl::init(false), cl::Hidden, 100 cl::desc("Enable performing ThinLTO.")); 101 102 cl::opt<bool> EnableHotColdSplit("hot-cold-split", 103 cl::desc("Enable hot-cold splitting pass")); 104 105 cl::opt<bool> EnableIROutliner("ir-outliner", cl::init(false), cl::Hidden, 106 cl::desc("Enable ir outliner pass")); 107 108 static cl::opt<bool> UseLoopVersioningLICM( 109 "enable-loop-versioning-licm", cl::init(false), cl::Hidden, 110 cl::desc("Enable the experimental Loop Versioning LICM pass")); 111 112 cl::opt<bool> 113 DisablePreInliner("disable-preinline", cl::init(false), cl::Hidden, 114 cl::desc("Disable pre-instrumentation inliner")); 115 116 cl::opt<int> PreInlineThreshold( 117 "preinline-threshold", cl::Hidden, cl::init(75), 118 cl::desc("Control the amount of inlining in pre-instrumentation inliner " 119 "(default = 75)")); 120 121 cl::opt<bool> 122 EnableGVNHoist("enable-gvn-hoist", 123 cl::desc("Enable the GVN hoisting pass (default = off)")); 124 125 static cl::opt<bool> 126 DisableLibCallsShrinkWrap("disable-libcalls-shrinkwrap", cl::init(false), 127 cl::Hidden, 128 cl::desc("Disable shrink-wrap library calls")); 129 130 cl::opt<bool> 131 EnableGVNSink("enable-gvn-sink", 132 cl::desc("Enable the GVN sinking pass (default = off)")); 133 134 // This option is used in simplifying testing SampleFDO optimizations for 135 // profile loading. 136 cl::opt<bool> 137 EnableCHR("enable-chr", cl::init(true), cl::Hidden, 138 cl::desc("Enable control height reduction optimization (CHR)")); 139 140 cl::opt<bool> FlattenedProfileUsed( 141 "flattened-profile-used", cl::init(false), cl::Hidden, 142 cl::desc("Indicate the sample profile being used is flattened, i.e., " 143 "no inline hierachy exists in the profile. ")); 144 145 cl::opt<bool> EnableOrderFileInstrumentation( 146 "enable-order-file-instrumentation", cl::init(false), cl::Hidden, 147 cl::desc("Enable order file instrumentation (default = off)")); 148 149 cl::opt<bool> EnableMatrix( 150 "enable-matrix", cl::init(false), cl::Hidden, 151 cl::desc("Enable lowering of the matrix intrinsics")); 152 153 cl::opt<bool> EnableConstraintElimination( 154 "enable-constraint-elimination", cl::init(false), cl::Hidden, 155 cl::desc( 156 "Enable pass to eliminate conditions based on linear constraints.")); 157 158 cl::opt<bool> EnableFunctionSpecialization( 159 "enable-function-specialization", cl::init(false), cl::Hidden, 160 cl::desc("Enable Function Specialization pass")); 161 162 cl::opt<AttributorRunOption> AttributorRun( 163 "attributor-enable", cl::Hidden, cl::init(AttributorRunOption::NONE), 164 cl::desc("Enable the attributor inter-procedural deduction pass."), 165 cl::values(clEnumValN(AttributorRunOption::ALL, "all", 166 "enable all attributor runs"), 167 clEnumValN(AttributorRunOption::MODULE, "module", 168 "enable module-wide attributor runs"), 169 clEnumValN(AttributorRunOption::CGSCC, "cgscc", 170 "enable call graph SCC attributor runs"), 171 clEnumValN(AttributorRunOption::NONE, "none", 172 "disable attributor runs"))); 173 174 extern cl::opt<bool> EnableKnowledgeRetention; 175 } // namespace llvm 176 177 PassManagerBuilder::PassManagerBuilder() { 178 OptLevel = 2; 179 SizeLevel = 0; 180 LibraryInfo = nullptr; 181 Inliner = nullptr; 182 DisableUnrollLoops = false; 183 SLPVectorize = false; 184 LoopVectorize = true; 185 LoopsInterleaved = true; 186 RerollLoops = RunLoopRerolling; 187 NewGVN = RunNewGVN; 188 LicmMssaOptCap = SetLicmMssaOptCap; 189 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 190 DisableGVNLoadPRE = false; 191 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 192 VerifyInput = false; 193 VerifyOutput = false; 194 MergeFunctions = false; 195 PrepareForLTO = false; 196 EnablePGOInstrGen = false; 197 EnablePGOCSInstrGen = false; 198 EnablePGOCSInstrUse = false; 199 PGOInstrGen = ""; 200 PGOInstrUse = ""; 201 PGOSampleUse = ""; 202 PrepareForThinLTO = EnablePrepareForThinLTO; 203 PerformThinLTO = EnablePerformThinLTO; 204 DivergentTarget = false; 205 CallGraphProfile = true; 206 } 207 208 PassManagerBuilder::~PassManagerBuilder() { 209 delete LibraryInfo; 210 delete Inliner; 211 } 212 213 /// Set of global extensions, automatically added as part of the standard set. 214 static ManagedStatic< 215 SmallVector<std::tuple<PassManagerBuilder::ExtensionPointTy, 216 PassManagerBuilder::ExtensionFn, 217 PassManagerBuilder::GlobalExtensionID>, 218 8>> 219 GlobalExtensions; 220 static PassManagerBuilder::GlobalExtensionID GlobalExtensionsCounter; 221 222 /// Check if GlobalExtensions is constructed and not empty. 223 /// Since GlobalExtensions is a managed static, calling 'empty()' will trigger 224 /// the construction of the object. 225 static bool GlobalExtensionsNotEmpty() { 226 return GlobalExtensions.isConstructed() && !GlobalExtensions->empty(); 227 } 228 229 PassManagerBuilder::GlobalExtensionID 230 PassManagerBuilder::addGlobalExtension(PassManagerBuilder::ExtensionPointTy Ty, 231 PassManagerBuilder::ExtensionFn Fn) { 232 auto ExtensionID = GlobalExtensionsCounter++; 233 GlobalExtensions->push_back(std::make_tuple(Ty, std::move(Fn), ExtensionID)); 234 return ExtensionID; 235 } 236 237 void PassManagerBuilder::removeGlobalExtension( 238 PassManagerBuilder::GlobalExtensionID ExtensionID) { 239 // RegisterStandardPasses may try to call this function after GlobalExtensions 240 // has already been destroyed; doing so should not generate an error. 241 if (!GlobalExtensions.isConstructed()) 242 return; 243 244 auto GlobalExtension = 245 llvm::find_if(*GlobalExtensions, [ExtensionID](const auto &elem) { 246 return std::get<2>(elem) == ExtensionID; 247 }); 248 assert(GlobalExtension != GlobalExtensions->end() && 249 "The extension ID to be removed should always be valid."); 250 251 GlobalExtensions->erase(GlobalExtension); 252 } 253 254 void PassManagerBuilder::addExtension(ExtensionPointTy Ty, ExtensionFn Fn) { 255 Extensions.push_back(std::make_pair(Ty, std::move(Fn))); 256 } 257 258 void PassManagerBuilder::addExtensionsToPM(ExtensionPointTy ETy, 259 legacy::PassManagerBase &PM) const { 260 if (GlobalExtensionsNotEmpty()) { 261 for (auto &Ext : *GlobalExtensions) { 262 if (std::get<0>(Ext) == ETy) 263 std::get<1>(Ext)(*this, PM); 264 } 265 } 266 for (unsigned i = 0, e = Extensions.size(); i != e; ++i) 267 if (Extensions[i].first == ETy) 268 Extensions[i].second(*this, PM); 269 } 270 271 void PassManagerBuilder::addInitialAliasAnalysisPasses( 272 legacy::PassManagerBase &PM) const { 273 switch (UseCFLAA) { 274 case ::CFLAAType::Steensgaard: 275 PM.add(createCFLSteensAAWrapperPass()); 276 break; 277 case ::CFLAAType::Andersen: 278 PM.add(createCFLAndersAAWrapperPass()); 279 break; 280 case ::CFLAAType::Both: 281 PM.add(createCFLSteensAAWrapperPass()); 282 PM.add(createCFLAndersAAWrapperPass()); 283 break; 284 default: 285 break; 286 } 287 288 // Add TypeBasedAliasAnalysis before BasicAliasAnalysis so that 289 // BasicAliasAnalysis wins if they disagree. This is intended to help 290 // support "obvious" type-punning idioms. 291 PM.add(createTypeBasedAAWrapperPass()); 292 PM.add(createScopedNoAliasAAWrapperPass()); 293 } 294 295 void PassManagerBuilder::populateFunctionPassManager( 296 legacy::FunctionPassManager &FPM) { 297 addExtensionsToPM(EP_EarlyAsPossible, FPM); 298 299 // Add LibraryInfo if we have some. 300 if (LibraryInfo) 301 FPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 302 303 // The backends do not handle matrix intrinsics currently. 304 // Make sure they are also lowered in O0. 305 // FIXME: A lightweight version of the pass should run in the backend 306 // pipeline on demand. 307 if (EnableMatrix && OptLevel == 0) 308 FPM.add(createLowerMatrixIntrinsicsMinimalPass()); 309 310 if (OptLevel == 0) return; 311 312 addInitialAliasAnalysisPasses(FPM); 313 314 // Lower llvm.expect to metadata before attempting transforms. 315 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 316 FPM.add(createLowerExpectIntrinsicPass()); 317 FPM.add(createCFGSimplificationPass()); 318 FPM.add(createSROAPass()); 319 FPM.add(createEarlyCSEPass()); 320 } 321 322 void PassManagerBuilder::addFunctionSimplificationPasses( 323 legacy::PassManagerBase &MPM) { 324 // Start of function pass. 325 // Break up aggregate allocas, using SSAUpdater. 326 assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!"); 327 MPM.add(createSROAPass()); 328 MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies 329 if (EnableKnowledgeRetention) 330 MPM.add(createAssumeSimplifyPass()); 331 332 if (OptLevel > 1) { 333 if (EnableGVNHoist) 334 MPM.add(createGVNHoistPass()); 335 if (EnableGVNSink) { 336 MPM.add(createGVNSinkPass()); 337 MPM.add(createCFGSimplificationPass( 338 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 339 } 340 } 341 342 if (EnableConstraintElimination) 343 MPM.add(createConstraintEliminationPass()); 344 345 if (OptLevel > 1) { 346 // Speculative execution if the target has divergent branches; otherwise nop. 347 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass()); 348 349 MPM.add(createJumpThreadingPass()); // Thread jumps. 350 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 351 } 352 MPM.add( 353 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 354 true))); // Merge & remove BBs 355 // Combine silly seq's 356 if (OptLevel > 2) 357 MPM.add(createAggressiveInstCombinerPass()); 358 MPM.add(createInstructionCombiningPass()); 359 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap) 360 MPM.add(createLibCallsShrinkWrapPass()); 361 addExtensionsToPM(EP_Peephole, MPM); 362 363 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 364 if (OptLevel > 1) 365 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 366 MPM.add( 367 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 368 true))); // Merge & remove BBs 369 MPM.add(createReassociatePass()); // Reassociate expressions 370 371 // The matrix extension can introduce large vector operations early, which can 372 // benefit from running vector-combine early on. 373 if (EnableMatrix) 374 MPM.add(createVectorCombinePass()); 375 376 // Begin the loop pass pipeline. 377 378 // The simple loop unswitch pass relies on separate cleanup passes. Schedule 379 // them first so when we re-process a loop they run before other loop 380 // passes. 381 MPM.add(createLoopInstSimplifyPass()); 382 MPM.add(createLoopSimplifyCFGPass()); 383 384 // Try to remove as much code from the loop header as possible, 385 // to reduce amount of IR that will have to be duplicated. However, 386 // do not perform speculative hoisting the first time as LICM 387 // will destroy metadata that may not need to be destroyed if run 388 // after loop rotation. 389 // TODO: Investigate promotion cap for O1. 390 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 391 /*AllowSpeculation=*/false)); 392 // Rotate Loop - disable header duplication at -Oz 393 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 394 // TODO: Investigate promotion cap for O1. 395 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 396 /*AllowSpeculation=*/true)); 397 MPM.add(createSimpleLoopUnswitchLegacyPass(OptLevel == 3)); 398 // FIXME: We break the loop pass pipeline here in order to do full 399 // simplifycfg. Eventually loop-simplifycfg should be enhanced to replace the 400 // need for this. 401 MPM.add(createCFGSimplificationPass( 402 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 403 MPM.add(createInstructionCombiningPass()); 404 // We resume loop passes creating a second loop pipeline here. 405 if (EnableLoopFlatten) { 406 MPM.add(createLoopFlattenPass()); // Flatten loops 407 MPM.add(createLoopSimplifyCFGPass()); 408 } 409 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 410 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 411 addExtensionsToPM(EP_LateLoopOptimizations, MPM); 412 MPM.add(createLoopDeletionPass()); // Delete dead loops 413 414 if (EnableLoopInterchange) 415 MPM.add(createLoopInterchangePass()); // Interchange loops 416 417 // Unroll small loops and perform peeling. 418 MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 419 ForgetAllSCEVInLoopUnroll)); 420 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 421 // This ends the loop pass pipelines. 422 423 // Break up allocas that may now be splittable after loop unrolling. 424 MPM.add(createSROAPass()); 425 426 if (OptLevel > 1) { 427 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 428 MPM.add(NewGVN ? createNewGVNPass() 429 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 430 } 431 MPM.add(createSCCPPass()); // Constant prop with SCCP 432 433 if (EnableConstraintElimination) 434 MPM.add(createConstraintEliminationPass()); 435 436 // Delete dead bit computations (instcombine runs after to fold away the dead 437 // computations, and then ADCE will run later to exploit any new DCE 438 // opportunities that creates). 439 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 440 441 // Run instcombine after redundancy elimination to exploit opportunities 442 // opened up by them. 443 MPM.add(createInstructionCombiningPass()); 444 addExtensionsToPM(EP_Peephole, MPM); 445 if (OptLevel > 1) { 446 if (EnableDFAJumpThreading && SizeLevel == 0) 447 MPM.add(createDFAJumpThreadingPass()); 448 449 MPM.add(createJumpThreadingPass()); // Thread jumps 450 MPM.add(createCorrelatedValuePropagationPass()); 451 } 452 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 453 454 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 455 // TODO: Investigate if this is too expensive at O1. 456 if (OptLevel > 1) { 457 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 458 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 459 /*AllowSpeculation=*/true)); 460 } 461 462 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 463 464 if (RerollLoops) 465 MPM.add(createLoopRerollPass()); 466 467 // Merge & remove BBs and sink & hoist common instructions. 468 MPM.add(createCFGSimplificationPass( 469 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true))); 470 // Clean up after everything. 471 MPM.add(createInstructionCombiningPass()); 472 addExtensionsToPM(EP_Peephole, MPM); 473 } 474 475 /// FIXME: Should LTO cause any differences to this set of passes? 476 void PassManagerBuilder::addVectorPasses(legacy::PassManagerBase &PM, 477 bool IsFullLTO) { 478 PM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize)); 479 480 if (IsFullLTO) { 481 // The vectorizer may have significantly shortened a loop body; unroll 482 // again. Unroll small loops to hide loop backedge latency and saturate any 483 // parallel execution resources of an out-of-order processor. We also then 484 // need to clean up redundancies and loop invariant code. 485 // FIXME: It would be really good to use a loop-integrated instruction 486 // combiner for cleanup here so that the unrolling and LICM can be pipelined 487 // across the loop nests. 488 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 489 if (EnableUnrollAndJam && !DisableUnrollLoops) 490 PM.add(createLoopUnrollAndJamPass(OptLevel)); 491 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 492 ForgetAllSCEVInLoopUnroll)); 493 PM.add(createWarnMissedTransformationsPass()); 494 } 495 496 if (!IsFullLTO) { 497 // Eliminate loads by forwarding stores from the previous iteration to loads 498 // of the current iteration. 499 PM.add(createLoopLoadEliminationPass()); 500 } 501 // Cleanup after the loop optimization passes. 502 PM.add(createInstructionCombiningPass()); 503 504 if (OptLevel > 1 && ExtraVectorizerPasses) { 505 // At higher optimization levels, try to clean up any runtime overlap and 506 // alignment checks inserted by the vectorizer. We want to track correlated 507 // runtime checks for two inner loops in the same outer loop, fold any 508 // common computations, hoist loop-invariant aspects out of any outer loop, 509 // and unswitch the runtime checks if possible. Once hoisted, we may have 510 // dead (or speculatable) control flows or more combining opportunities. 511 PM.add(createEarlyCSEPass()); 512 PM.add(createCorrelatedValuePropagationPass()); 513 PM.add(createInstructionCombiningPass()); 514 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 515 /*AllowSpeculation=*/true)); 516 PM.add(createSimpleLoopUnswitchLegacyPass()); 517 PM.add(createCFGSimplificationPass( 518 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 519 PM.add(createInstructionCombiningPass()); 520 } 521 522 // Now that we've formed fast to execute loop structures, we do further 523 // optimizations. These are run afterward as they might block doing complex 524 // analyses and transforms such as what are needed for loop vectorization. 525 526 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 527 // GVN, loop transforms, and others have already run, so it's now better to 528 // convert to more optimized IR using more aggressive simplify CFG options. 529 // The extra sinking transform can create larger basic blocks, so do this 530 // before SLP vectorization. 531 PM.add(createCFGSimplificationPass(SimplifyCFGOptions() 532 .forwardSwitchCondToPhi(true) 533 .convertSwitchRangeToICmp(true) 534 .convertSwitchToLookupTable(true) 535 .needCanonicalLoops(false) 536 .hoistCommonInsts(true) 537 .sinkCommonInsts(true))); 538 539 if (IsFullLTO) { 540 PM.add(createSCCPPass()); // Propagate exposed constants 541 PM.add(createInstructionCombiningPass()); // Clean up again 542 PM.add(createBitTrackingDCEPass()); 543 } 544 545 // Optimize parallel scalar instruction chains into SIMD instructions. 546 if (SLPVectorize) { 547 PM.add(createSLPVectorizerPass()); 548 if (OptLevel > 1 && ExtraVectorizerPasses) 549 PM.add(createEarlyCSEPass()); 550 } 551 552 // Enhance/cleanup vector code. 553 PM.add(createVectorCombinePass()); 554 555 if (!IsFullLTO) { 556 addExtensionsToPM(EP_Peephole, PM); 557 PM.add(createInstructionCombiningPass()); 558 559 if (EnableUnrollAndJam && !DisableUnrollLoops) { 560 // Unroll and Jam. We do this before unroll but need to be in a separate 561 // loop pass manager in order for the outer loop to be processed by 562 // unroll and jam before the inner loop is unrolled. 563 PM.add(createLoopUnrollAndJamPass(OptLevel)); 564 } 565 566 // Unroll small loops 567 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 568 ForgetAllSCEVInLoopUnroll)); 569 570 if (!DisableUnrollLoops) { 571 // LoopUnroll may generate some redundency to cleanup. 572 PM.add(createInstructionCombiningPass()); 573 574 // Runtime unrolling will introduce runtime check in loop prologue. If the 575 // unrolled loop is a inner loop, then the prologue will be inside the 576 // outer loop. LICM pass can help to promote the runtime check out if the 577 // checked value is loop invariant. 578 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 579 /*AllowSpeculation=*/true)); 580 } 581 582 PM.add(createWarnMissedTransformationsPass()); 583 } 584 585 // After vectorization and unrolling, assume intrinsics may tell us more 586 // about pointer alignments. 587 PM.add(createAlignmentFromAssumptionsPass()); 588 589 if (IsFullLTO) 590 PM.add(createInstructionCombiningPass()); 591 } 592 593 void PassManagerBuilder::populateModulePassManager( 594 legacy::PassManagerBase &MPM) { 595 MPM.add(createAnnotation2MetadataLegacyPass()); 596 597 if (!PGOSampleUse.empty()) { 598 MPM.add(createPruneEHPass()); 599 // In ThinLTO mode, when flattened profile is used, all the available 600 // profile information will be annotated in PreLink phase so there is 601 // no need to load the profile again in PostLink. 602 if (!(FlattenedProfileUsed && PerformThinLTO)) 603 MPM.add(createSampleProfileLoaderPass(PGOSampleUse)); 604 } 605 606 // Allow forcing function attributes as a debugging and tuning aid. 607 MPM.add(createForceFunctionAttrsLegacyPass()); 608 609 // If all optimizations are disabled, just run the always-inline pass and, 610 // if enabled, the function merging pass. 611 if (OptLevel == 0) { 612 if (Inliner) { 613 MPM.add(Inliner); 614 Inliner = nullptr; 615 } 616 617 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 618 // creates a CGSCC pass manager, but we don't want to add extensions into 619 // that pass manager. To prevent this we insert a no-op module pass to reset 620 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 621 // builds. The function merging pass is 622 if (MergeFunctions) 623 MPM.add(createMergeFunctionsPass()); 624 else if (GlobalExtensionsNotEmpty() || !Extensions.empty()) 625 MPM.add(createBarrierNoopPass()); 626 627 if (PerformThinLTO) { 628 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 629 // Drop available_externally and unreferenced globals. This is necessary 630 // with ThinLTO in order to avoid leaving undefined references to dead 631 // globals in the object file. 632 MPM.add(createEliminateAvailableExternallyPass()); 633 MPM.add(createGlobalDCEPass()); 634 } 635 636 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 637 638 if (PrepareForLTO || PrepareForThinLTO) { 639 MPM.add(createCanonicalizeAliasesPass()); 640 // Rename anon globals to be able to export them in the summary. 641 // This has to be done after we add the extensions to the pass manager 642 // as there could be passes (e.g. Adddress sanitizer) which introduce 643 // new unnamed globals. 644 MPM.add(createNameAnonGlobalPass()); 645 } 646 647 MPM.add(createAnnotationRemarksLegacyPass()); 648 return; 649 } 650 651 // Add LibraryInfo if we have some. 652 if (LibraryInfo) 653 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 654 655 addInitialAliasAnalysisPasses(MPM); 656 657 // For ThinLTO there are two passes of indirect call promotion. The 658 // first is during the compile phase when PerformThinLTO=false and 659 // intra-module indirect call targets are promoted. The second is during 660 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 661 // inter-module indirect calls. For that we perform indirect call promotion 662 // earlier in the pass pipeline, here before globalopt. Otherwise imported 663 // available_externally functions look unreferenced and are removed. 664 if (PerformThinLTO) { 665 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 666 } 667 668 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops 669 // as it will change the CFG too much to make the 2nd profile annotation 670 // in backend more difficult. 671 bool PrepareForThinLTOUsingPGOSampleProfile = 672 PrepareForThinLTO && !PGOSampleUse.empty(); 673 if (PrepareForThinLTOUsingPGOSampleProfile) 674 DisableUnrollLoops = true; 675 676 // Infer attributes about declarations if possible. 677 MPM.add(createInferFunctionAttrsLegacyPass()); 678 679 // Infer attributes on declarations, call sites, arguments, etc. 680 if (AttributorRun & AttributorRunOption::MODULE) 681 MPM.add(createAttributorLegacyPass()); 682 683 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 684 685 if (OptLevel > 2) 686 MPM.add(createCallSiteSplittingPass()); 687 688 // Propage constant function arguments by specializing the functions. 689 if (OptLevel > 2 && EnableFunctionSpecialization) 690 MPM.add(createFunctionSpecializationPass()); 691 692 MPM.add(createIPSCCPPass()); // IP SCCP 693 MPM.add(createCalledValuePropagationPass()); 694 695 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 696 // Promote any localized global vars. 697 MPM.add(createPromoteMemoryToRegisterPass()); 698 699 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 700 701 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE 702 addExtensionsToPM(EP_Peephole, MPM); 703 MPM.add( 704 createCFGSimplificationPass(SimplifyCFGOptions().convertSwitchRangeToICmp( 705 true))); // Clean up after IPCP & DAE 706 707 // We add a module alias analysis pass here. In part due to bugs in the 708 // analysis infrastructure this "works" in that the analysis stays alive 709 // for the entire SCC pass run below. 710 MPM.add(createGlobalsAAWrapperPass()); 711 712 // Start of CallGraph SCC passes. 713 MPM.add(createPruneEHPass()); // Remove dead EH info 714 bool RunInliner = false; 715 if (Inliner) { 716 MPM.add(Inliner); 717 Inliner = nullptr; 718 RunInliner = true; 719 } 720 721 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 722 if (AttributorRun & AttributorRunOption::CGSCC) 723 MPM.add(createAttributorCGSCCLegacyPass()); 724 725 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 726 // there are no OpenMP runtime calls present in the module. 727 if (OptLevel > 1) 728 MPM.add(createOpenMPOptCGSCCLegacyPass()); 729 730 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 731 732 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 733 addFunctionSimplificationPasses(MPM); 734 735 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 736 // pass manager that we are specifically trying to avoid. To prevent this 737 // we must insert a no-op module pass to reset the pass manager. 738 MPM.add(createBarrierNoopPass()); 739 740 if (RunPartialInlining) 741 MPM.add(createPartialInliningPass()); 742 743 if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO) 744 // Remove avail extern fns and globals definitions if we aren't 745 // compiling an object file for later LTO. For LTO we want to preserve 746 // these so they are eligible for inlining at link-time. Note if they 747 // are unreferenced they will be removed by GlobalDCE later, so 748 // this only impacts referenced available externally globals. 749 // Eventually they will be suppressed during codegen, but eliminating 750 // here enables more opportunity for GlobalDCE as it may make 751 // globals referenced by available external functions dead 752 // and saves running remaining passes on the eliminated functions. 753 MPM.add(createEliminateAvailableExternallyPass()); 754 755 if (EnableOrderFileInstrumentation) 756 MPM.add(createInstrOrderFilePass()); 757 758 MPM.add(createReversePostOrderFunctionAttrsPass()); 759 760 // The inliner performs some kind of dead code elimination as it goes, 761 // but there are cases that are not really caught by it. We might 762 // at some point consider teaching the inliner about them, but it 763 // is OK for now to run GlobalOpt + GlobalDCE in tandem as their 764 // benefits generally outweight the cost, making the whole pipeline 765 // faster. 766 if (RunInliner) { 767 MPM.add(createGlobalOptimizerPass()); 768 MPM.add(createGlobalDCEPass()); 769 } 770 771 // If we are planning to perform ThinLTO later, let's not bloat the code with 772 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 773 // during ThinLTO and perform the rest of the optimizations afterward. 774 if (PrepareForThinLTO) { 775 // Ensure we perform any last passes, but do so before renaming anonymous 776 // globals in case the passes add any. 777 addExtensionsToPM(EP_OptimizerLast, MPM); 778 MPM.add(createCanonicalizeAliasesPass()); 779 // Rename anon globals to be able to export them in the summary. 780 MPM.add(createNameAnonGlobalPass()); 781 return; 782 } 783 784 if (PerformThinLTO) 785 // Optimize globals now when performing ThinLTO, this enables more 786 // optimizations later. 787 MPM.add(createGlobalOptimizerPass()); 788 789 // Scheduling LoopVersioningLICM when inlining is over, because after that 790 // we may see more accurate aliasing. Reason to run this late is that too 791 // early versioning may prevent further inlining due to increase of code 792 // size. By placing it just after inlining other optimizations which runs 793 // later might get benefit of no-alias assumption in clone loop. 794 if (UseLoopVersioningLICM) { 795 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 796 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap, 797 /*AllowSpeculation=*/true)); 798 } 799 800 // We add a fresh GlobalsModRef run at this point. This is particularly 801 // useful as the above will have inlined, DCE'ed, and function-attr 802 // propagated everything. We should at this point have a reasonably minimal 803 // and richly annotated call graph. By computing aliasing and mod/ref 804 // information for all local globals here, the late loop passes and notably 805 // the vectorizer will be able to use them to help recognize vectorizable 806 // memory operations. 807 // 808 // Note that this relies on a bug in the pass manager which preserves 809 // a module analysis into a function pass pipeline (and throughout it) so 810 // long as the first function pass doesn't invalidate the module analysis. 811 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 812 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 813 // (doing nothing preserves it as it is required to be conservatively 814 // correct in the face of IR changes). 815 MPM.add(createGlobalsAAWrapperPass()); 816 817 MPM.add(createFloat2IntPass()); 818 MPM.add(createLowerConstantIntrinsicsPass()); 819 820 if (EnableMatrix) { 821 MPM.add(createLowerMatrixIntrinsicsPass()); 822 // CSE the pointer arithmetic of the column vectors. This allows alias 823 // analysis to establish no-aliasing between loads and stores of different 824 // columns of the same matrix. 825 MPM.add(createEarlyCSEPass(false)); 826 } 827 828 addExtensionsToPM(EP_VectorizerStart, MPM); 829 830 // Re-rotate loops in all our loop nests. These may have fallout out of 831 // rotated form due to GVN or other transformations, and the vectorizer relies 832 // on the rotated form. Disable header duplication at -Oz. 833 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 834 835 // Distribute loops to allow partial vectorization. I.e. isolate dependences 836 // into separate loop that would otherwise inhibit vectorization. This is 837 // currently only performed for loops marked with the metadata 838 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 839 MPM.add(createLoopDistributePass()); 840 841 addVectorPasses(MPM, /* IsFullLTO */ false); 842 843 // FIXME: We shouldn't bother with this anymore. 844 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 845 846 // GlobalOpt already deletes dead functions and globals, at -O2 try a 847 // late pass of GlobalDCE. It is capable of deleting dead cycles. 848 if (OptLevel > 1) { 849 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 850 MPM.add(createConstantMergePass()); // Merge dup global constants 851 } 852 853 // See comment in the new PM for justification of scheduling splitting at 854 // this stage (\ref buildModuleSimplificationPipeline). 855 if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO)) 856 MPM.add(createHotColdSplittingPass()); 857 858 if (EnableIROutliner) 859 MPM.add(createIROutlinerPass()); 860 861 if (MergeFunctions) 862 MPM.add(createMergeFunctionsPass()); 863 864 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 865 // canonicalization pass that enables other optimizations. As a result, 866 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 867 // result too early. 868 MPM.add(createLoopSinkPass()); 869 // Get rid of LCSSA nodes. 870 MPM.add(createInstSimplifyLegacyPass()); 871 872 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 873 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 874 // flattening of blocks. 875 MPM.add(createDivRemPairsPass()); 876 877 // LoopSink (and other loop passes since the last simplifyCFG) might have 878 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 879 MPM.add(createCFGSimplificationPass( 880 SimplifyCFGOptions().convertSwitchRangeToICmp(true))); 881 882 addExtensionsToPM(EP_OptimizerLast, MPM); 883 884 if (PrepareForLTO) { 885 MPM.add(createCanonicalizeAliasesPass()); 886 // Rename anon globals to be able to handle them in the summary 887 MPM.add(createNameAnonGlobalPass()); 888 } 889 890 MPM.add(createAnnotationRemarksLegacyPass()); 891 } 892 893 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 894 PassManagerBuilder *PMB = new PassManagerBuilder(); 895 return wrap(PMB); 896 } 897 898 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 899 PassManagerBuilder *Builder = unwrap(PMB); 900 delete Builder; 901 } 902 903 void 904 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 905 unsigned OptLevel) { 906 PassManagerBuilder *Builder = unwrap(PMB); 907 Builder->OptLevel = OptLevel; 908 } 909 910 void 911 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 912 unsigned SizeLevel) { 913 PassManagerBuilder *Builder = unwrap(PMB); 914 Builder->SizeLevel = SizeLevel; 915 } 916 917 void 918 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 919 LLVMBool Value) { 920 // NOTE: The DisableUnitAtATime switch has been removed. 921 } 922 923 void 924 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 925 LLVMBool Value) { 926 PassManagerBuilder *Builder = unwrap(PMB); 927 Builder->DisableUnrollLoops = Value; 928 } 929 930 void 931 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 932 LLVMBool Value) { 933 // NOTE: The simplify-libcalls pass has been removed. 934 } 935 936 void 937 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 938 unsigned Threshold) { 939 PassManagerBuilder *Builder = unwrap(PMB); 940 Builder->Inliner = createFunctionInliningPass(Threshold); 941 } 942 943 void 944 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 945 LLVMPassManagerRef PM) { 946 PassManagerBuilder *Builder = unwrap(PMB); 947 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 948 Builder->populateFunctionPassManager(*FPM); 949 } 950 951 void 952 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 953 LLVMPassManagerRef PM) { 954 PassManagerBuilder *Builder = unwrap(PMB); 955 legacy::PassManagerBase *MPM = unwrap(PM); 956 Builder->populateModulePassManager(*MPM); 957 } 958