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 FPM.add(createCFGSimplificationPass()); 320 FPM.add(createSROAPass()); 321 FPM.add(createEarlyCSEPass()); 322 FPM.add(createLowerExpectIntrinsicPass()); 323 } 324 325 // Do PGO instrumentation generation or use pass as the option specified. 326 void PassManagerBuilder::addPGOInstrPasses(legacy::PassManagerBase &MPM, 327 bool IsCS = false) { 328 if (IsCS) { 329 if (!EnablePGOCSInstrGen && !EnablePGOCSInstrUse) 330 return; 331 } else if (!EnablePGOInstrGen && PGOInstrUse.empty() && PGOSampleUse.empty()) 332 return; 333 334 // Perform the preinline and cleanup passes for O1 and above. 335 // We will not do this inline for context sensitive PGO (when IsCS is true). 336 if (OptLevel > 0 && !DisablePreInliner && PGOSampleUse.empty() && !IsCS) { 337 // Create preinline pass. We construct an InlineParams object and specify 338 // the threshold here to avoid the command line options of the regular 339 // inliner to influence pre-inlining. The only fields of InlineParams we 340 // care about are DefaultThreshold and HintThreshold. 341 InlineParams IP; 342 IP.DefaultThreshold = PreInlineThreshold; 343 // FIXME: The hint threshold has the same value used by the regular inliner 344 // when not optimzing for size. This should probably be lowered after 345 // performance testing. 346 // Use PreInlineThreshold for both -Os and -Oz. Not running preinliner makes 347 // the instrumented binary unusably large. Even if PreInlineThreshold is not 348 // correct thresold for -Oz, it is better than not running preinliner. 349 IP.HintThreshold = SizeLevel > 0 ? PreInlineThreshold : 325; 350 351 MPM.add(createFunctionInliningPass(IP)); 352 MPM.add(createSROAPass()); 353 MPM.add(createEarlyCSEPass()); // Catch trivial redundancies 354 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 355 MPM.add(createInstructionCombiningPass()); // Combine silly seq's 356 addExtensionsToPM(EP_Peephole, MPM); 357 } 358 if ((EnablePGOInstrGen && !IsCS) || (EnablePGOCSInstrGen && IsCS)) { 359 MPM.add(createPGOInstrumentationGenLegacyPass(IsCS)); 360 // Add the profile lowering pass. 361 InstrProfOptions Options; 362 if (!PGOInstrGen.empty()) 363 Options.InstrProfileOutput = PGOInstrGen; 364 Options.DoCounterPromotion = true; 365 Options.UseBFIInPromotion = IsCS; 366 MPM.add(createLoopRotatePass()); 367 MPM.add(createInstrProfilingLegacyPass(Options, IsCS)); 368 } 369 if (!PGOInstrUse.empty()) 370 MPM.add(createPGOInstrumentationUseLegacyPass(PGOInstrUse, IsCS)); 371 // Indirect call promotion that promotes intra-module targets only. 372 // For ThinLTO this is done earlier due to interactions with globalopt 373 // for imported functions. We don't run this at -O0. 374 if (OptLevel > 0 && !IsCS) 375 MPM.add( 376 createPGOIndirectCallPromotionLegacyPass(false, !PGOSampleUse.empty())); 377 } 378 void PassManagerBuilder::addFunctionSimplificationPasses( 379 legacy::PassManagerBase &MPM) { 380 // Start of function pass. 381 // Break up aggregate allocas, using SSAUpdater. 382 assert(OptLevel >= 1 && "Calling function optimizer with no optimization level!"); 383 MPM.add(createSROAPass()); 384 MPM.add(createEarlyCSEPass(true /* Enable mem-ssa. */)); // Catch trivial redundancies 385 if (EnableKnowledgeRetention) 386 MPM.add(createAssumeSimplifyPass()); 387 388 if (OptLevel > 1) { 389 if (EnableGVNHoist) 390 MPM.add(createGVNHoistPass()); 391 if (EnableGVNSink) { 392 MPM.add(createGVNSinkPass()); 393 MPM.add(createCFGSimplificationPass()); 394 } 395 } 396 397 if (EnableConstraintElimination) 398 MPM.add(createConstraintEliminationPass()); 399 400 if (OptLevel > 1) { 401 // Speculative execution if the target has divergent branches; otherwise nop. 402 MPM.add(createSpeculativeExecutionIfHasBranchDivergencePass()); 403 404 MPM.add(createJumpThreadingPass()); // Thread jumps. 405 MPM.add(createCorrelatedValuePropagationPass()); // Propagate conditionals 406 } 407 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 408 // Combine silly seq's 409 if (OptLevel > 2) 410 MPM.add(createAggressiveInstCombinerPass()); 411 MPM.add(createInstructionCombiningPass()); 412 if (SizeLevel == 0 && !DisableLibCallsShrinkWrap) 413 MPM.add(createLibCallsShrinkWrapPass()); 414 addExtensionsToPM(EP_Peephole, MPM); 415 416 // Optimize memory intrinsic calls based on the profiled size information. 417 if (SizeLevel == 0) 418 MPM.add(createPGOMemOPSizeOptLegacyPass()); 419 420 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 421 if (OptLevel > 1) 422 MPM.add(createTailCallEliminationPass()); // Eliminate tail calls 423 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 424 MPM.add(createReassociatePass()); // Reassociate expressions 425 426 // Begin the loop pass pipeline. 427 if (EnableSimpleLoopUnswitch) { 428 // The simple loop unswitch pass relies on separate cleanup passes. Schedule 429 // them first so when we re-process a loop they run before other loop 430 // passes. 431 MPM.add(createLoopInstSimplifyPass()); 432 MPM.add(createLoopSimplifyCFGPass()); 433 } 434 // Try to remove as much code from the loop header as possible, 435 // to reduce amount of IR that will have to be duplicated. 436 // TODO: Investigate promotion cap for O1. 437 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 438 // Rotate Loop - disable header duplication at -Oz 439 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 440 // TODO: Investigate promotion cap for O1. 441 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 442 if (EnableSimpleLoopUnswitch) 443 MPM.add(createSimpleLoopUnswitchLegacyPass()); 444 else 445 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 446 // FIXME: We break the loop pass pipeline here in order to do full 447 // simplify-cfg. Eventually loop-simplifycfg should be enhanced to replace the 448 // need for this. 449 MPM.add(createCFGSimplificationPass()); 450 MPM.add(createInstructionCombiningPass()); 451 // We resume loop passes creating a second loop pipeline here. 452 if (EnableLoopFlatten) { 453 MPM.add(createLoopFlattenPass()); // Flatten loops 454 MPM.add(createLoopSimplifyCFGPass()); 455 } 456 MPM.add(createLoopIdiomPass()); // Recognize idioms like memset. 457 MPM.add(createIndVarSimplifyPass()); // Canonicalize indvars 458 addExtensionsToPM(EP_LateLoopOptimizations, MPM); 459 MPM.add(createLoopDeletionPass()); // Delete dead loops 460 461 if (EnableLoopInterchange) 462 MPM.add(createLoopInterchangePass()); // Interchange loops 463 464 // Unroll small loops and perform peeling. 465 MPM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 466 ForgetAllSCEVInLoopUnroll)); 467 addExtensionsToPM(EP_LoopOptimizerEnd, MPM); 468 // This ends the loop pass pipelines. 469 470 // Break up allocas that may now be splittable after loop unrolling. 471 MPM.add(createSROAPass()); 472 473 if (OptLevel > 1) { 474 MPM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds 475 MPM.add(NewGVN ? createNewGVNPass() 476 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies 477 } 478 MPM.add(createSCCPPass()); // Constant prop with SCCP 479 480 if (EnableConstraintElimination) 481 MPM.add(createConstraintEliminationPass()); 482 483 // Delete dead bit computations (instcombine runs after to fold away the dead 484 // computations, and then ADCE will run later to exploit any new DCE 485 // opportunities that creates). 486 MPM.add(createBitTrackingDCEPass()); // Delete dead bit computations 487 488 // Run instcombine after redundancy elimination to exploit opportunities 489 // opened up by them. 490 MPM.add(createInstructionCombiningPass()); 491 addExtensionsToPM(EP_Peephole, MPM); 492 if (OptLevel > 1) { 493 MPM.add(createJumpThreadingPass()); // Thread jumps 494 MPM.add(createCorrelatedValuePropagationPass()); 495 } 496 MPM.add(createAggressiveDCEPass()); // Delete dead instructions 497 498 MPM.add(createMemCpyOptPass()); // Remove memcpy / form memset 499 // TODO: Investigate if this is too expensive at O1. 500 if (OptLevel > 1) { 501 MPM.add(createDeadStoreEliminationPass()); // Delete dead stores 502 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 503 } 504 505 addExtensionsToPM(EP_ScalarOptimizerLate, MPM); 506 507 if (RerollLoops) 508 MPM.add(createLoopRerollPass()); 509 510 MPM.add(createCFGSimplificationPass()); // Merge & remove BBs 511 // Clean up after everything. 512 MPM.add(createInstructionCombiningPass()); 513 addExtensionsToPM(EP_Peephole, MPM); 514 515 if (EnableCHR && OptLevel >= 3 && 516 (!PGOInstrUse.empty() || !PGOSampleUse.empty() || EnablePGOCSInstrGen)) 517 MPM.add(createControlHeightReductionLegacyPass()); 518 } 519 520 void PassManagerBuilder::populateModulePassManager( 521 legacy::PassManagerBase &MPM) { 522 // Whether this is a default or *LTO pre-link pipeline. The FullLTO post-link 523 // is handled separately, so just check this is not the ThinLTO post-link. 524 bool DefaultOrPreLinkPipeline = !PerformThinLTO; 525 526 MPM.add(createAnnotation2MetadataLegacyPass()); 527 528 if (!PGOSampleUse.empty()) { 529 MPM.add(createPruneEHPass()); 530 // In ThinLTO mode, when flattened profile is used, all the available 531 // profile information will be annotated in PreLink phase so there is 532 // no need to load the profile again in PostLink. 533 if (!(FlattenedProfileUsed && PerformThinLTO)) 534 MPM.add(createSampleProfileLoaderPass(PGOSampleUse)); 535 } 536 537 // Allow forcing function attributes as a debugging and tuning aid. 538 MPM.add(createForceFunctionAttrsLegacyPass()); 539 540 // If all optimizations are disabled, just run the always-inline pass and, 541 // if enabled, the function merging pass. 542 if (OptLevel == 0) { 543 addPGOInstrPasses(MPM); 544 if (Inliner) { 545 MPM.add(Inliner); 546 Inliner = nullptr; 547 } 548 549 // FIXME: The BarrierNoopPass is a HACK! The inliner pass above implicitly 550 // creates a CGSCC pass manager, but we don't want to add extensions into 551 // that pass manager. To prevent this we insert a no-op module pass to reset 552 // the pass manager to get the same behavior as EP_OptimizerLast in non-O0 553 // builds. The function merging pass is 554 if (MergeFunctions) 555 MPM.add(createMergeFunctionsPass()); 556 else if (GlobalExtensionsNotEmpty() || !Extensions.empty()) 557 MPM.add(createBarrierNoopPass()); 558 559 if (PerformThinLTO) { 560 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 561 // Drop available_externally and unreferenced globals. This is necessary 562 // with ThinLTO in order to avoid leaving undefined references to dead 563 // globals in the object file. 564 MPM.add(createEliminateAvailableExternallyPass()); 565 MPM.add(createGlobalDCEPass()); 566 } 567 568 addExtensionsToPM(EP_EnabledOnOptLevel0, MPM); 569 570 if (PrepareForLTO || PrepareForThinLTO) { 571 MPM.add(createCanonicalizeAliasesPass()); 572 // Rename anon globals to be able to export them in the summary. 573 // This has to be done after we add the extensions to the pass manager 574 // as there could be passes (e.g. Adddress sanitizer) which introduce 575 // new unnamed globals. 576 MPM.add(createNameAnonGlobalPass()); 577 } 578 579 MPM.add(createAnnotationRemarksLegacyPass()); 580 return; 581 } 582 583 // Add LibraryInfo if we have some. 584 if (LibraryInfo) 585 MPM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 586 587 addInitialAliasAnalysisPasses(MPM); 588 589 // For ThinLTO there are two passes of indirect call promotion. The 590 // first is during the compile phase when PerformThinLTO=false and 591 // intra-module indirect call targets are promoted. The second is during 592 // the ThinLTO backend when PerformThinLTO=true, when we promote imported 593 // inter-module indirect calls. For that we perform indirect call promotion 594 // earlier in the pass pipeline, here before globalopt. Otherwise imported 595 // available_externally functions look unreferenced and are removed. 596 if (PerformThinLTO) { 597 MPM.add(createPGOIndirectCallPromotionLegacyPass(/*InLTO = */ true, 598 !PGOSampleUse.empty())); 599 MPM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 600 } 601 602 // For SamplePGO in ThinLTO compile phase, we do not want to unroll loops 603 // as it will change the CFG too much to make the 2nd profile annotation 604 // in backend more difficult. 605 bool PrepareForThinLTOUsingPGOSampleProfile = 606 PrepareForThinLTO && !PGOSampleUse.empty(); 607 if (PrepareForThinLTOUsingPGOSampleProfile) 608 DisableUnrollLoops = true; 609 610 // Infer attributes about declarations if possible. 611 MPM.add(createInferFunctionAttrsLegacyPass()); 612 613 // Infer attributes on declarations, call sites, arguments, etc. 614 if (AttributorRun & AttributorRunOption::MODULE) 615 MPM.add(createAttributorLegacyPass()); 616 617 addExtensionsToPM(EP_ModuleOptimizerEarly, MPM); 618 619 if (OptLevel > 2) 620 MPM.add(createCallSiteSplittingPass()); 621 622 MPM.add(createIPSCCPPass()); // IP SCCP 623 MPM.add(createCalledValuePropagationPass()); 624 625 MPM.add(createGlobalOptimizerPass()); // Optimize out global vars 626 // Promote any localized global vars. 627 MPM.add(createPromoteMemoryToRegisterPass()); 628 629 MPM.add(createDeadArgEliminationPass()); // Dead argument elimination 630 631 MPM.add(createInstructionCombiningPass()); // Clean up after IPCP & DAE 632 addExtensionsToPM(EP_Peephole, MPM); 633 MPM.add(createCFGSimplificationPass()); // Clean up after IPCP & DAE 634 635 // For SamplePGO in ThinLTO compile phase, we do not want to do indirect 636 // call promotion as it will change the CFG too much to make the 2nd 637 // profile annotation in backend more difficult. 638 // PGO instrumentation is added during the compile phase for ThinLTO, do 639 // not run it a second time 640 if (DefaultOrPreLinkPipeline && !PrepareForThinLTOUsingPGOSampleProfile) 641 addPGOInstrPasses(MPM); 642 643 // Create profile COMDAT variables. Lld linker wants to see all variables 644 // before the LTO/ThinLTO link since it needs to resolve symbols/comdats. 645 if (!PerformThinLTO && EnablePGOCSInstrGen) 646 MPM.add(createPGOInstrumentationGenCreateVarLegacyPass(PGOInstrGen)); 647 648 // We add a module alias analysis pass here. In part due to bugs in the 649 // analysis infrastructure this "works" in that the analysis stays alive 650 // for the entire SCC pass run below. 651 MPM.add(createGlobalsAAWrapperPass()); 652 653 // Start of CallGraph SCC passes. 654 MPM.add(createPruneEHPass()); // Remove dead EH info 655 bool RunInliner = false; 656 if (Inliner) { 657 MPM.add(Inliner); 658 Inliner = nullptr; 659 RunInliner = true; 660 } 661 662 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 663 if (AttributorRun & AttributorRunOption::CGSCC) 664 MPM.add(createAttributorCGSCCLegacyPass()); 665 666 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 667 // there are no OpenMP runtime calls present in the module. 668 if (OptLevel > 1) 669 MPM.add(createOpenMPOptLegacyPass()); 670 671 MPM.add(createPostOrderFunctionAttrsLegacyPass()); 672 if (OptLevel > 2) 673 MPM.add(createArgumentPromotionPass()); // Scalarize uninlined fn args 674 675 addExtensionsToPM(EP_CGSCCOptimizerLate, MPM); 676 addFunctionSimplificationPasses(MPM); 677 678 // FIXME: This is a HACK! The inliner pass above implicitly creates a CGSCC 679 // pass manager that we are specifically trying to avoid. To prevent this 680 // we must insert a no-op module pass to reset the pass manager. 681 MPM.add(createBarrierNoopPass()); 682 683 if (RunPartialInlining) 684 MPM.add(createPartialInliningPass()); 685 686 if (OptLevel > 1 && !PrepareForLTO && !PrepareForThinLTO) 687 // Remove avail extern fns and globals definitions if we aren't 688 // compiling an object file for later LTO. For LTO we want to preserve 689 // these so they are eligible for inlining at link-time. Note if they 690 // are unreferenced they will be removed by GlobalDCE later, so 691 // this only impacts referenced available externally globals. 692 // Eventually they will be suppressed during codegen, but eliminating 693 // here enables more opportunity for GlobalDCE as it may make 694 // globals referenced by available external functions dead 695 // and saves running remaining passes on the eliminated functions. 696 MPM.add(createEliminateAvailableExternallyPass()); 697 698 // CSFDO instrumentation and use pass. Don't invoke this for Prepare pass 699 // for LTO and ThinLTO -- The actual pass will be called after all inlines 700 // are performed. 701 // Need to do this after COMDAT variables have been eliminated, 702 // (i.e. after EliminateAvailableExternallyPass). 703 if (!(PrepareForLTO || PrepareForThinLTO)) 704 addPGOInstrPasses(MPM, /* IsCS */ true); 705 706 if (EnableOrderFileInstrumentation) 707 MPM.add(createInstrOrderFilePass()); 708 709 MPM.add(createReversePostOrderFunctionAttrsPass()); 710 711 // The inliner performs some kind of dead code elimination as it goes, 712 // but there are cases that are not really caught by it. We might 713 // at some point consider teaching the inliner about them, but it 714 // is OK for now to run GlobalOpt + GlobalDCE in tandem as their 715 // benefits generally outweight the cost, making the whole pipeline 716 // faster. 717 if (RunInliner) { 718 MPM.add(createGlobalOptimizerPass()); 719 MPM.add(createGlobalDCEPass()); 720 } 721 722 // If we are planning to perform ThinLTO later, let's not bloat the code with 723 // unrolling/vectorization/... now. We'll first run the inliner + CGSCC passes 724 // during ThinLTO and perform the rest of the optimizations afterward. 725 if (PrepareForThinLTO) { 726 // Ensure we perform any last passes, but do so before renaming anonymous 727 // globals in case the passes add any. 728 addExtensionsToPM(EP_OptimizerLast, MPM); 729 MPM.add(createCanonicalizeAliasesPass()); 730 // Rename anon globals to be able to export them in the summary. 731 MPM.add(createNameAnonGlobalPass()); 732 return; 733 } 734 735 if (PerformThinLTO) 736 // Optimize globals now when performing ThinLTO, this enables more 737 // optimizations later. 738 MPM.add(createGlobalOptimizerPass()); 739 740 // Scheduling LoopVersioningLICM when inlining is over, because after that 741 // we may see more accurate aliasing. Reason to run this late is that too 742 // early versioning may prevent further inlining due to increase of code 743 // size. By placing it just after inlining other optimizations which runs 744 // later might get benefit of no-alias assumption in clone loop. 745 if (UseLoopVersioningLICM) { 746 MPM.add(createLoopVersioningLICMPass()); // Do LoopVersioningLICM 747 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 748 } 749 750 // We add a fresh GlobalsModRef run at this point. This is particularly 751 // useful as the above will have inlined, DCE'ed, and function-attr 752 // propagated everything. We should at this point have a reasonably minimal 753 // and richly annotated call graph. By computing aliasing and mod/ref 754 // information for all local globals here, the late loop passes and notably 755 // the vectorizer will be able to use them to help recognize vectorizable 756 // memory operations. 757 // 758 // Note that this relies on a bug in the pass manager which preserves 759 // a module analysis into a function pass pipeline (and throughout it) so 760 // long as the first function pass doesn't invalidate the module analysis. 761 // Thus both Float2Int and LoopRotate have to preserve AliasAnalysis for 762 // this to work. Fortunately, it is trivial to preserve AliasAnalysis 763 // (doing nothing preserves it as it is required to be conservatively 764 // correct in the face of IR changes). 765 MPM.add(createGlobalsAAWrapperPass()); 766 767 MPM.add(createFloat2IntPass()); 768 MPM.add(createLowerConstantIntrinsicsPass()); 769 770 if (EnableMatrix) { 771 MPM.add(createLowerMatrixIntrinsicsPass()); 772 // CSE the pointer arithmetic of the column vectors. This allows alias 773 // analysis to establish no-aliasing between loads and stores of different 774 // columns of the same matrix. 775 MPM.add(createEarlyCSEPass(false)); 776 } 777 778 addExtensionsToPM(EP_VectorizerStart, MPM); 779 780 // Re-rotate loops in all our loop nests. These may have fallout out of 781 // rotated form due to GVN or other transformations, and the vectorizer relies 782 // on the rotated form. Disable header duplication at -Oz. 783 MPM.add(createLoopRotatePass(SizeLevel == 2 ? 0 : -1, PrepareForLTO)); 784 785 // Distribute loops to allow partial vectorization. I.e. isolate dependences 786 // into separate loop that would otherwise inhibit vectorization. This is 787 // currently only performed for loops marked with the metadata 788 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 789 MPM.add(createLoopDistributePass()); 790 791 MPM.add(createLoopVectorizePass(!LoopsInterleaved, !LoopVectorize)); 792 793 // Eliminate loads by forwarding stores from the previous iteration to loads 794 // of the current iteration. 795 MPM.add(createLoopLoadEliminationPass()); 796 797 // FIXME: Because of #pragma vectorize enable, the passes below are always 798 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when 799 // on -O1 and no #pragma is found). Would be good to have these two passes 800 // as function calls, so that we can only pass them when the vectorizer 801 // changed the code. 802 MPM.add(createInstructionCombiningPass()); 803 if (OptLevel > 1 && ExtraVectorizerPasses) { 804 // At higher optimization levels, try to clean up any runtime overlap and 805 // alignment checks inserted by the vectorizer. We want to track correllated 806 // runtime checks for two inner loops in the same outer loop, fold any 807 // common computations, hoist loop-invariant aspects out of any outer loop, 808 // and unswitch the runtime checks if possible. Once hoisted, we may have 809 // dead (or speculatable) control flows or more combining opportunities. 810 MPM.add(createEarlyCSEPass()); 811 MPM.add(createCorrelatedValuePropagationPass()); 812 MPM.add(createInstructionCombiningPass()); 813 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 814 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 815 MPM.add(createCFGSimplificationPass()); 816 MPM.add(createInstructionCombiningPass()); 817 } 818 819 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 820 // GVN, loop transforms, and others have already run, so it's now better to 821 // convert to more optimized IR using more aggressive simplify CFG options. 822 // The extra sinking transform can create larger basic blocks, so do this 823 // before SLP vectorization. 824 // FIXME: study whether hoisting and/or sinking of common instructions should 825 // be delayed until after SLP vectorizer. 826 MPM.add(createCFGSimplificationPass(SimplifyCFGOptions() 827 .forwardSwitchCondToPhi(true) 828 .convertSwitchToLookupTable(true) 829 .needCanonicalLoops(false) 830 .hoistCommonInsts(true) 831 .sinkCommonInsts(true))); 832 833 if (SLPVectorize) { 834 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 835 if (OptLevel > 1 && ExtraVectorizerPasses) { 836 MPM.add(createEarlyCSEPass()); 837 } 838 } 839 840 // Enhance/cleanup vector code. 841 MPM.add(createVectorCombinePass()); 842 843 addExtensionsToPM(EP_Peephole, MPM); 844 MPM.add(createInstructionCombiningPass()); 845 846 if (EnableUnrollAndJam && !DisableUnrollLoops) { 847 // Unroll and Jam. We do this before unroll but need to be in a separate 848 // loop pass manager in order for the outer loop to be processed by 849 // unroll and jam before the inner loop is unrolled. 850 MPM.add(createLoopUnrollAndJamPass(OptLevel)); 851 } 852 853 // Unroll small loops 854 MPM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 855 ForgetAllSCEVInLoopUnroll)); 856 857 if (!DisableUnrollLoops) { 858 // LoopUnroll may generate some redundency to cleanup. 859 MPM.add(createInstructionCombiningPass()); 860 861 // Runtime unrolling will introduce runtime check in loop prologue. If the 862 // unrolled loop is a inner loop, then the prologue will be inside the 863 // outer loop. LICM pass can help to promote the runtime check out if the 864 // checked value is loop invariant. 865 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 866 } 867 868 MPM.add(createWarnMissedTransformationsPass()); 869 870 // After vectorization and unrolling, assume intrinsics may tell us more 871 // about pointer alignments. 872 MPM.add(createAlignmentFromAssumptionsPass()); 873 874 // FIXME: We shouldn't bother with this anymore. 875 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 876 877 // GlobalOpt already deletes dead functions and globals, at -O2 try a 878 // late pass of GlobalDCE. It is capable of deleting dead cycles. 879 if (OptLevel > 1) { 880 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 881 MPM.add(createConstantMergePass()); // Merge dup global constants 882 } 883 884 // See comment in the new PM for justification of scheduling splitting at 885 // this stage (\ref buildModuleSimplificationPipeline). 886 if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO)) 887 MPM.add(createHotColdSplittingPass()); 888 889 if (EnableIROutliner) 890 MPM.add(createIROutlinerPass()); 891 892 if (MergeFunctions) 893 MPM.add(createMergeFunctionsPass()); 894 895 // Add Module flag "CG Profile" based on Branch Frequency Information. 896 if (CallGraphProfile) 897 MPM.add(createCGProfileLegacyPass()); 898 899 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 900 // canonicalization pass that enables other optimizations. As a result, 901 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 902 // result too early. 903 MPM.add(createLoopSinkPass()); 904 // Get rid of LCSSA nodes. 905 MPM.add(createInstSimplifyLegacyPass()); 906 907 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 908 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 909 // flattening of blocks. 910 MPM.add(createDivRemPairsPass()); 911 912 // LoopSink (and other loop passes since the last simplifyCFG) might have 913 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 914 MPM.add(createCFGSimplificationPass()); 915 916 addExtensionsToPM(EP_OptimizerLast, MPM); 917 918 if (PrepareForLTO) { 919 MPM.add(createCanonicalizeAliasesPass()); 920 // Rename anon globals to be able to handle them in the summary 921 MPM.add(createNameAnonGlobalPass()); 922 } 923 924 MPM.add(createAnnotationRemarksLegacyPass()); 925 } 926 927 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 928 // Load sample profile before running the LTO optimization pipeline. 929 if (!PGOSampleUse.empty()) { 930 PM.add(createPruneEHPass()); 931 PM.add(createSampleProfileLoaderPass(PGOSampleUse)); 932 } 933 934 // Remove unused virtual tables to improve the quality of code generated by 935 // whole-program devirtualization and bitset lowering. 936 PM.add(createGlobalDCEPass()); 937 938 // Provide AliasAnalysis services for optimizations. 939 addInitialAliasAnalysisPasses(PM); 940 941 // Allow forcing function attributes as a debugging and tuning aid. 942 PM.add(createForceFunctionAttrsLegacyPass()); 943 944 // Infer attributes about declarations if possible. 945 PM.add(createInferFunctionAttrsLegacyPass()); 946 947 if (OptLevel > 1) { 948 // Split call-site with more constrained arguments. 949 PM.add(createCallSiteSplittingPass()); 950 951 // Indirect call promotion. This should promote all the targets that are 952 // left by the earlier promotion pass that promotes intra-module targets. 953 // This two-step promotion is to save the compile time. For LTO, it should 954 // produce the same result as if we only do promotion here. 955 PM.add( 956 createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty())); 957 958 // Propagate constants at call sites into the functions they call. This 959 // opens opportunities for globalopt (and inlining) by substituting function 960 // pointers passed as arguments to direct uses of functions. 961 PM.add(createIPSCCPPass()); 962 963 // Attach metadata to indirect call sites indicating the set of functions 964 // they may target at run-time. This should follow IPSCCP. 965 PM.add(createCalledValuePropagationPass()); 966 967 // Infer attributes on declarations, call sites, arguments, etc. 968 if (AttributorRun & AttributorRunOption::MODULE) 969 PM.add(createAttributorLegacyPass()); 970 } 971 972 // Infer attributes about definitions. The readnone attribute in particular is 973 // required for virtual constant propagation. 974 PM.add(createPostOrderFunctionAttrsLegacyPass()); 975 PM.add(createReversePostOrderFunctionAttrsPass()); 976 977 // Split globals using inrange annotations on GEP indices. This can help 978 // improve the quality of generated code when virtual constant propagation or 979 // control flow integrity are enabled. 980 PM.add(createGlobalSplitPass()); 981 982 // Apply whole-program devirtualization and virtual constant propagation. 983 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 984 985 // That's all we need at opt level 1. 986 if (OptLevel == 1) 987 return; 988 989 // Now that we internalized some globals, see if we can hack on them! 990 PM.add(createGlobalOptimizerPass()); 991 // Promote any localized global vars. 992 PM.add(createPromoteMemoryToRegisterPass()); 993 994 // Linking modules together can lead to duplicated global constants, only 995 // keep one copy of each constant. 996 PM.add(createConstantMergePass()); 997 998 // Remove unused arguments from functions. 999 PM.add(createDeadArgEliminationPass()); 1000 1001 // Reduce the code after globalopt and ipsccp. Both can open up significant 1002 // simplification opportunities, and both can propagate functions through 1003 // function pointers. When this happens, we often have to resolve varargs 1004 // calls, etc, so let instcombine do this. 1005 if (OptLevel > 2) 1006 PM.add(createAggressiveInstCombinerPass()); 1007 PM.add(createInstructionCombiningPass()); 1008 addExtensionsToPM(EP_Peephole, PM); 1009 1010 // Inline small functions 1011 bool RunInliner = Inliner; 1012 if (RunInliner) { 1013 PM.add(Inliner); 1014 Inliner = nullptr; 1015 } 1016 1017 PM.add(createPruneEHPass()); // Remove dead EH info. 1018 1019 // CSFDO instrumentation and use pass. 1020 addPGOInstrPasses(PM, /* IsCS */ true); 1021 1022 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 1023 if (AttributorRun & AttributorRunOption::CGSCC) 1024 PM.add(createAttributorCGSCCLegacyPass()); 1025 1026 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 1027 // there are no OpenMP runtime calls present in the module. 1028 if (OptLevel > 1) 1029 PM.add(createOpenMPOptLegacyPass()); 1030 1031 // Optimize globals again if we ran the inliner. 1032 if (RunInliner) 1033 PM.add(createGlobalOptimizerPass()); 1034 PM.add(createGlobalDCEPass()); // Remove dead functions. 1035 1036 // If we didn't decide to inline a function, check to see if we can 1037 // transform it to pass arguments by value instead of by reference. 1038 PM.add(createArgumentPromotionPass()); 1039 1040 // The IPO passes may leave cruft around. Clean up after them. 1041 PM.add(createInstructionCombiningPass()); 1042 addExtensionsToPM(EP_Peephole, PM); 1043 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1044 1045 // Break up allocas 1046 PM.add(createSROAPass()); 1047 1048 // LTO provides additional opportunities for tailcall elimination due to 1049 // link-time inlining, and visibility of nocapture attribute. 1050 if (OptLevel > 1) 1051 PM.add(createTailCallEliminationPass()); 1052 1053 // Infer attributes on declarations, call sites, arguments, etc. 1054 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 1055 // Run a few AA driven optimizations here and now, to cleanup the code. 1056 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 1057 1058 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 1059 PM.add(NewGVN ? createNewGVNPass() 1060 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 1061 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 1062 1063 // Nuke dead stores. 1064 PM.add(createDeadStoreEliminationPass()); 1065 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 1066 1067 // More loops are countable; try to optimize them. 1068 if (EnableLoopFlatten) 1069 PM.add(createLoopFlattenPass()); 1070 PM.add(createIndVarSimplifyPass()); 1071 PM.add(createLoopDeletionPass()); 1072 if (EnableLoopInterchange) 1073 PM.add(createLoopInterchangePass()); 1074 1075 if (EnableConstraintElimination) 1076 PM.add(createConstraintEliminationPass()); 1077 1078 // Unroll small loops and perform peeling. 1079 PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 1080 ForgetAllSCEVInLoopUnroll)); 1081 PM.add(createLoopDistributePass()); 1082 PM.add(createLoopVectorizePass(true, !LoopVectorize)); 1083 // The vectorizer may have significantly shortened a loop body; unroll again. 1084 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 1085 ForgetAllSCEVInLoopUnroll)); 1086 1087 PM.add(createWarnMissedTransformationsPass()); 1088 1089 // Now that we've optimized loops (in particular loop induction variables), 1090 // we may have exposed more scalar opportunities. Run parts of the scalar 1091 // optimizer again at this point. 1092 PM.add(createInstructionCombiningPass()); // Initial cleanup 1093 PM.add(createCFGSimplificationPass(SimplifyCFGOptions() // if-convert 1094 .hoistCommonInsts(true))); 1095 PM.add(createSCCPPass()); // Propagate exposed constants 1096 PM.add(createInstructionCombiningPass()); // Clean up again 1097 PM.add(createBitTrackingDCEPass()); 1098 1099 // More scalar chains could be vectorized due to more alias information 1100 if (SLPVectorize) 1101 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 1102 1103 PM.add(createVectorCombinePass()); // Clean up partial vectorization. 1104 1105 // After vectorization, assume intrinsics may tell us more about pointer 1106 // alignments. 1107 PM.add(createAlignmentFromAssumptionsPass()); 1108 1109 // Cleanup and simplify the code after the scalar optimizations. 1110 PM.add(createInstructionCombiningPass()); 1111 addExtensionsToPM(EP_Peephole, PM); 1112 1113 PM.add(createJumpThreadingPass(/*FreezeSelectCond*/ true)); 1114 } 1115 1116 void PassManagerBuilder::addLateLTOOptimizationPasses( 1117 legacy::PassManagerBase &PM) { 1118 // See comment in the new PM for justification of scheduling splitting at 1119 // this stage (\ref buildLTODefaultPipeline). 1120 if (EnableHotColdSplit) 1121 PM.add(createHotColdSplittingPass()); 1122 1123 // Delete basic blocks, which optimization passes may have killed. 1124 PM.add( 1125 createCFGSimplificationPass(SimplifyCFGOptions().hoistCommonInsts(true))); 1126 1127 // Drop bodies of available externally objects to improve GlobalDCE. 1128 PM.add(createEliminateAvailableExternallyPass()); 1129 1130 // Now that we have optimized the program, discard unreachable functions. 1131 PM.add(createGlobalDCEPass()); 1132 1133 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 1134 // currently it damages debug info. 1135 if (MergeFunctions) 1136 PM.add(createMergeFunctionsPass()); 1137 } 1138 1139 void PassManagerBuilder::populateThinLTOPassManager( 1140 legacy::PassManagerBase &PM) { 1141 PerformThinLTO = true; 1142 if (LibraryInfo) 1143 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1144 1145 if (VerifyInput) 1146 PM.add(createVerifierPass()); 1147 1148 if (ImportSummary) { 1149 // This pass imports type identifier resolutions for whole-program 1150 // devirtualization and CFI. It must run early because other passes may 1151 // disturb the specific instruction patterns that these passes look for, 1152 // creating dependencies on resolutions that may not appear in the summary. 1153 // 1154 // For example, GVN may transform the pattern assume(type.test) appearing in 1155 // two basic blocks into assume(phi(type.test, type.test)), which would 1156 // transform a dependency on a WPD resolution into a dependency on a type 1157 // identifier resolution for CFI. 1158 // 1159 // Also, WPD has access to more precise information than ICP and can 1160 // devirtualize more effectively, so it should operate on the IR first. 1161 PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary)); 1162 PM.add(createLowerTypeTestsPass(nullptr, ImportSummary)); 1163 } 1164 1165 populateModulePassManager(PM); 1166 1167 if (VerifyOutput) 1168 PM.add(createVerifierPass()); 1169 PerformThinLTO = false; 1170 } 1171 1172 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) { 1173 if (LibraryInfo) 1174 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1175 1176 if (VerifyInput) 1177 PM.add(createVerifierPass()); 1178 1179 addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM); 1180 1181 if (OptLevel != 0) 1182 addLTOOptimizationPasses(PM); 1183 else { 1184 // The whole-program-devirt pass needs to run at -O0 because only it knows 1185 // about the llvm.type.checked.load intrinsic: it needs to both lower the 1186 // intrinsic itself and handle it in the summary. 1187 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 1188 } 1189 1190 // Create a function that performs CFI checks for cross-DSO calls with targets 1191 // in the current module. 1192 PM.add(createCrossDSOCFIPass()); 1193 1194 // Lower type metadata and the type.test intrinsic. This pass supports Clang's 1195 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at 1196 // link time if CFI is enabled. The pass does nothing if CFI is disabled. 1197 PM.add(createLowerTypeTestsPass(ExportSummary, nullptr)); 1198 // Run a second time to clean up any type tests left behind by WPD for use 1199 // in ICP (which is performed earlier than this in the regular LTO pipeline). 1200 PM.add(createLowerTypeTestsPass(nullptr, nullptr, true)); 1201 1202 if (OptLevel != 0) 1203 addLateLTOOptimizationPasses(PM); 1204 1205 addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM); 1206 1207 PM.add(createAnnotationRemarksLegacyPass()); 1208 1209 if (VerifyOutput) 1210 PM.add(createVerifierPass()); 1211 } 1212 1213 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 1214 PassManagerBuilder *PMB = new PassManagerBuilder(); 1215 return wrap(PMB); 1216 } 1217 1218 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 1219 PassManagerBuilder *Builder = unwrap(PMB); 1220 delete Builder; 1221 } 1222 1223 void 1224 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 1225 unsigned OptLevel) { 1226 PassManagerBuilder *Builder = unwrap(PMB); 1227 Builder->OptLevel = OptLevel; 1228 } 1229 1230 void 1231 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 1232 unsigned SizeLevel) { 1233 PassManagerBuilder *Builder = unwrap(PMB); 1234 Builder->SizeLevel = SizeLevel; 1235 } 1236 1237 void 1238 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 1239 LLVMBool Value) { 1240 // NOTE: The DisableUnitAtATime switch has been removed. 1241 } 1242 1243 void 1244 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 1245 LLVMBool Value) { 1246 PassManagerBuilder *Builder = unwrap(PMB); 1247 Builder->DisableUnrollLoops = Value; 1248 } 1249 1250 void 1251 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 1252 LLVMBool Value) { 1253 // NOTE: The simplify-libcalls pass has been removed. 1254 } 1255 1256 void 1257 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 1258 unsigned Threshold) { 1259 PassManagerBuilder *Builder = unwrap(PMB); 1260 Builder->Inliner = createFunctionInliningPass(Threshold); 1261 } 1262 1263 void 1264 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 1265 LLVMPassManagerRef PM) { 1266 PassManagerBuilder *Builder = unwrap(PMB); 1267 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 1268 Builder->populateFunctionPassManager(*FPM); 1269 } 1270 1271 void 1272 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 1273 LLVMPassManagerRef PM) { 1274 PassManagerBuilder *Builder = unwrap(PMB); 1275 legacy::PassManagerBase *MPM = unwrap(PM); 1276 Builder->populateModulePassManager(*MPM); 1277 } 1278 1279 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 1280 LLVMPassManagerRef PM, 1281 LLVMBool Internalize, 1282 LLVMBool RunInliner) { 1283 PassManagerBuilder *Builder = unwrap(PMB); 1284 legacy::PassManagerBase *LPM = unwrap(PM); 1285 1286 // A small backwards compatibility hack. populateLTOPassManager used to take 1287 // an RunInliner option. 1288 if (RunInliner && !Builder->Inliner) 1289 Builder->Inliner = createFunctionInliningPass(); 1290 1291 Builder->populateLTOPassManager(*LPM); 1292 } 1293