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