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