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), 104 cl::ZeroOrMore, 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::ZeroOrMore, 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::ZeroOrMore, 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 745 // Eliminate loads by forwarding stores from the previous iteration to loads 746 // of the current iteration. 747 MPM.add(createLoopLoadEliminationPass()); 748 749 // FIXME: Because of #pragma vectorize enable, the passes below are always 750 // inserted in the pipeline, even when the vectorizer doesn't run (ex. when 751 // on -O1 and no #pragma is found). Would be good to have these two passes 752 // as function calls, so that we can only pass them when the vectorizer 753 // changed the code. 754 MPM.add(createInstructionCombiningPass()); 755 if (OptLevel > 1 && ExtraVectorizerPasses) { 756 // At higher optimization levels, try to clean up any runtime overlap and 757 // alignment checks inserted by the vectorizer. We want to track correllated 758 // runtime checks for two inner loops in the same outer loop, fold any 759 // common computations, hoist loop-invariant aspects out of any outer loop, 760 // and unswitch the runtime checks if possible. Once hoisted, we may have 761 // dead (or speculatable) control flows or more combining opportunities. 762 MPM.add(createEarlyCSEPass()); 763 MPM.add(createCorrelatedValuePropagationPass()); 764 MPM.add(createInstructionCombiningPass()); 765 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 766 MPM.add(createLoopUnswitchPass(SizeLevel || OptLevel < 3, DivergentTarget)); 767 MPM.add(createCFGSimplificationPass()); 768 MPM.add(createInstructionCombiningPass()); 769 } 770 771 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 772 // GVN, loop transforms, and others have already run, so it's now better to 773 // convert to more optimized IR using more aggressive simplify CFG options. 774 // The extra sinking transform can create larger basic blocks, so do this 775 // before SLP vectorization. 776 MPM.add(createCFGSimplificationPass(1, true, true, false, true)); 777 778 if (SLPVectorize) { 779 MPM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 780 if (OptLevel > 1 && ExtraVectorizerPasses) { 781 MPM.add(createEarlyCSEPass()); 782 } 783 } 784 785 // Enhance/cleanup vector code. 786 MPM.add(createVectorCombinePass()); 787 788 addExtensionsToPM(EP_Peephole, MPM); 789 MPM.add(createInstructionCombiningPass()); 790 791 if (EnableUnrollAndJam && !DisableUnrollLoops) { 792 // Unroll and Jam. We do this before unroll but need to be in a separate 793 // loop pass manager in order for the outer loop to be processed by 794 // unroll and jam before the inner loop is unrolled. 795 MPM.add(createLoopUnrollAndJamPass(OptLevel)); 796 } 797 798 // Unroll small loops 799 MPM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 800 ForgetAllSCEVInLoopUnroll)); 801 802 if (!DisableUnrollLoops) { 803 // LoopUnroll may generate some redundency to cleanup. 804 MPM.add(createInstructionCombiningPass()); 805 806 // Runtime unrolling will introduce runtime check in loop prologue. If the 807 // unrolled loop is a inner loop, then the prologue will be inside the 808 // outer loop. LICM pass can help to promote the runtime check out if the 809 // checked value is loop invariant. 810 MPM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 811 } 812 813 MPM.add(createWarnMissedTransformationsPass()); 814 815 // After vectorization and unrolling, assume intrinsics may tell us more 816 // about pointer alignments. 817 MPM.add(createAlignmentFromAssumptionsPass()); 818 819 // FIXME: We shouldn't bother with this anymore. 820 MPM.add(createStripDeadPrototypesPass()); // Get rid of dead prototypes 821 822 // GlobalOpt already deletes dead functions and globals, at -O2 try a 823 // late pass of GlobalDCE. It is capable of deleting dead cycles. 824 if (OptLevel > 1) { 825 MPM.add(createGlobalDCEPass()); // Remove dead fns and globals. 826 MPM.add(createConstantMergePass()); // Merge dup global constants 827 } 828 829 // See comment in the new PM for justification of scheduling splitting at 830 // this stage (\ref buildModuleSimplificationPipeline). 831 if (EnableHotColdSplit && !(PrepareForLTO || PrepareForThinLTO)) 832 MPM.add(createHotColdSplittingPass()); 833 834 if (MergeFunctions) 835 MPM.add(createMergeFunctionsPass()); 836 837 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 838 // canonicalization pass that enables other optimizations. As a result, 839 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 840 // result too early. 841 MPM.add(createLoopSinkPass()); 842 // Get rid of LCSSA nodes. 843 MPM.add(createInstSimplifyLegacyPass()); 844 845 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 846 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 847 // flattening of blocks. 848 MPM.add(createDivRemPairsPass()); 849 850 // LoopSink (and other loop passes since the last simplifyCFG) might have 851 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 852 MPM.add(createCFGSimplificationPass()); 853 854 addExtensionsToPM(EP_OptimizerLast, MPM); 855 856 if (PrepareForLTO) { 857 MPM.add(createCanonicalizeAliasesPass()); 858 // Rename anon globals to be able to handle them in the summary 859 MPM.add(createNameAnonGlobalPass()); 860 } 861 } 862 863 void PassManagerBuilder::addLTOOptimizationPasses(legacy::PassManagerBase &PM) { 864 // Load sample profile before running the LTO optimization pipeline. 865 if (!PGOSampleUse.empty()) { 866 PM.add(createPruneEHPass()); 867 PM.add(createSampleProfileLoaderPass(PGOSampleUse)); 868 } 869 870 // Remove unused virtual tables to improve the quality of code generated by 871 // whole-program devirtualization and bitset lowering. 872 PM.add(createGlobalDCEPass()); 873 874 // Provide AliasAnalysis services for optimizations. 875 addInitialAliasAnalysisPasses(PM); 876 877 // Allow forcing function attributes as a debugging and tuning aid. 878 PM.add(createForceFunctionAttrsLegacyPass()); 879 880 // Infer attributes about declarations if possible. 881 PM.add(createInferFunctionAttrsLegacyPass()); 882 883 if (OptLevel > 1) { 884 // Split call-site with more constrained arguments. 885 PM.add(createCallSiteSplittingPass()); 886 887 // Indirect call promotion. This should promote all the targets that are 888 // left by the earlier promotion pass that promotes intra-module targets. 889 // This two-step promotion is to save the compile time. For LTO, it should 890 // produce the same result as if we only do promotion here. 891 PM.add( 892 createPGOIndirectCallPromotionLegacyPass(true, !PGOSampleUse.empty())); 893 894 // Propagate constants at call sites into the functions they call. This 895 // opens opportunities for globalopt (and inlining) by substituting function 896 // pointers passed as arguments to direct uses of functions. 897 PM.add(createIPSCCPPass()); 898 899 // Attach metadata to indirect call sites indicating the set of functions 900 // they may target at run-time. This should follow IPSCCP. 901 PM.add(createCalledValuePropagationPass()); 902 903 // Infer attributes on declarations, call sites, arguments, etc. 904 if (AttributorRun & AttributorRunOption::MODULE) 905 PM.add(createAttributorLegacyPass()); 906 } 907 908 // Infer attributes about definitions. The readnone attribute in particular is 909 // required for virtual constant propagation. 910 PM.add(createPostOrderFunctionAttrsLegacyPass()); 911 PM.add(createReversePostOrderFunctionAttrsPass()); 912 913 // Split globals using inrange annotations on GEP indices. This can help 914 // improve the quality of generated code when virtual constant propagation or 915 // control flow integrity are enabled. 916 PM.add(createGlobalSplitPass()); 917 918 // Apply whole-program devirtualization and virtual constant propagation. 919 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 920 921 // That's all we need at opt level 1. 922 if (OptLevel == 1) 923 return; 924 925 // Now that we internalized some globals, see if we can hack on them! 926 PM.add(createGlobalOptimizerPass()); 927 // Promote any localized global vars. 928 PM.add(createPromoteMemoryToRegisterPass()); 929 930 // Linking modules together can lead to duplicated global constants, only 931 // keep one copy of each constant. 932 PM.add(createConstantMergePass()); 933 934 // Remove unused arguments from functions. 935 PM.add(createDeadArgEliminationPass()); 936 937 // Reduce the code after globalopt and ipsccp. Both can open up significant 938 // simplification opportunities, and both can propagate functions through 939 // function pointers. When this happens, we often have to resolve varargs 940 // calls, etc, so let instcombine do this. 941 if (OptLevel > 2) 942 PM.add(createAggressiveInstCombinerPass()); 943 PM.add(createInstructionCombiningPass()); 944 addExtensionsToPM(EP_Peephole, PM); 945 946 // Inline small functions 947 bool RunInliner = Inliner; 948 if (RunInliner) { 949 PM.add(Inliner); 950 Inliner = nullptr; 951 } 952 953 PM.add(createPruneEHPass()); // Remove dead EH info. 954 955 // CSFDO instrumentation and use pass. 956 addPGOInstrPasses(PM, /* IsCS */ true); 957 958 // Infer attributes on declarations, call sites, arguments, etc. for an SCC. 959 if (AttributorRun & AttributorRunOption::CGSCC) 960 PM.add(createAttributorCGSCCLegacyPass()); 961 962 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 963 // there are no OpenMP runtime calls present in the module. 964 if (OptLevel > 1) 965 PM.add(createOpenMPOptLegacyPass()); 966 967 // Optimize globals again if we ran the inliner. 968 if (RunInliner) 969 PM.add(createGlobalOptimizerPass()); 970 PM.add(createGlobalDCEPass()); // Remove dead functions. 971 972 // If we didn't decide to inline a function, check to see if we can 973 // transform it to pass arguments by value instead of by reference. 974 PM.add(createArgumentPromotionPass()); 975 976 // The IPO passes may leave cruft around. Clean up after them. 977 PM.add(createInstructionCombiningPass()); 978 addExtensionsToPM(EP_Peephole, PM); 979 PM.add(createJumpThreadingPass()); 980 981 // Break up allocas 982 PM.add(createSROAPass()); 983 984 // LTO provides additional opportunities for tailcall elimination due to 985 // link-time inlining, and visibility of nocapture attribute. 986 if (OptLevel > 1) 987 PM.add(createTailCallEliminationPass()); 988 989 // Infer attributes on declarations, call sites, arguments, etc. 990 PM.add(createPostOrderFunctionAttrsLegacyPass()); // Add nocapture. 991 // Run a few AA driven optimizations here and now, to cleanup the code. 992 PM.add(createGlobalsAAWrapperPass()); // IP alias analysis. 993 994 PM.add(createLICMPass(LicmMssaOptCap, LicmMssaNoAccForPromotionCap)); 995 PM.add(createMergedLoadStoreMotionPass()); // Merge ld/st in diamonds. 996 PM.add(NewGVN ? createNewGVNPass() 997 : createGVNPass(DisableGVNLoadPRE)); // Remove redundancies. 998 PM.add(createMemCpyOptPass()); // Remove dead memcpys. 999 1000 // Nuke dead stores. 1001 PM.add(createDeadStoreEliminationPass()); 1002 1003 // More loops are countable; try to optimize them. 1004 PM.add(createIndVarSimplifyPass()); 1005 PM.add(createLoopDeletionPass()); 1006 if (EnableLoopInterchange) 1007 PM.add(createLoopInterchangePass()); 1008 1009 // Unroll small loops 1010 PM.add(createSimpleLoopUnrollPass(OptLevel, DisableUnrollLoops, 1011 ForgetAllSCEVInLoopUnroll)); 1012 PM.add(createLoopVectorizePass(true, !LoopVectorize)); 1013 // The vectorizer may have significantly shortened a loop body; unroll again. 1014 PM.add(createLoopUnrollPass(OptLevel, DisableUnrollLoops, 1015 ForgetAllSCEVInLoopUnroll)); 1016 1017 PM.add(createWarnMissedTransformationsPass()); 1018 1019 // Now that we've optimized loops (in particular loop induction variables), 1020 // we may have exposed more scalar opportunities. Run parts of the scalar 1021 // optimizer again at this point. 1022 PM.add(createInstructionCombiningPass()); // Initial cleanup 1023 PM.add(createCFGSimplificationPass()); // if-convert 1024 PM.add(createSCCPPass()); // Propagate exposed constants 1025 PM.add(createInstructionCombiningPass()); // Clean up again 1026 PM.add(createBitTrackingDCEPass()); 1027 1028 // More scalar chains could be vectorized due to more alias information 1029 if (SLPVectorize) 1030 PM.add(createSLPVectorizerPass()); // Vectorize parallel scalar chains. 1031 1032 PM.add(createVectorCombinePass()); // Clean up partial vectorization. 1033 1034 // After vectorization, assume intrinsics may tell us more about pointer 1035 // alignments. 1036 PM.add(createAlignmentFromAssumptionsPass()); 1037 1038 // Cleanup and simplify the code after the scalar optimizations. 1039 PM.add(createInstructionCombiningPass()); 1040 addExtensionsToPM(EP_Peephole, PM); 1041 1042 PM.add(createJumpThreadingPass()); 1043 } 1044 1045 void PassManagerBuilder::addLateLTOOptimizationPasses( 1046 legacy::PassManagerBase &PM) { 1047 // See comment in the new PM for justification of scheduling splitting at 1048 // this stage (\ref buildLTODefaultPipeline). 1049 if (EnableHotColdSplit) 1050 PM.add(createHotColdSplittingPass()); 1051 1052 // Delete basic blocks, which optimization passes may have killed. 1053 PM.add(createCFGSimplificationPass()); 1054 1055 // Drop bodies of available externally objects to improve GlobalDCE. 1056 PM.add(createEliminateAvailableExternallyPass()); 1057 1058 // Now that we have optimized the program, discard unreachable functions. 1059 PM.add(createGlobalDCEPass()); 1060 1061 // FIXME: this is profitable (for compiler time) to do at -O0 too, but 1062 // currently it damages debug info. 1063 if (MergeFunctions) 1064 PM.add(createMergeFunctionsPass()); 1065 } 1066 1067 void PassManagerBuilder::populateThinLTOPassManager( 1068 legacy::PassManagerBase &PM) { 1069 PerformThinLTO = true; 1070 if (LibraryInfo) 1071 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1072 1073 if (VerifyInput) 1074 PM.add(createVerifierPass()); 1075 1076 if (ImportSummary) { 1077 // These passes import type identifier resolutions for whole-program 1078 // devirtualization and CFI. They must run early because other passes may 1079 // disturb the specific instruction patterns that these passes look for, 1080 // creating dependencies on resolutions that may not appear in the summary. 1081 // 1082 // For example, GVN may transform the pattern assume(type.test) appearing in 1083 // two basic blocks into assume(phi(type.test, type.test)), which would 1084 // transform a dependency on a WPD resolution into a dependency on a type 1085 // identifier resolution for CFI. 1086 // 1087 // Also, WPD has access to more precise information than ICP and can 1088 // devirtualize more effectively, so it should operate on the IR first. 1089 PM.add(createWholeProgramDevirtPass(nullptr, ImportSummary)); 1090 PM.add(createLowerTypeTestsPass(nullptr, ImportSummary)); 1091 } 1092 1093 populateModulePassManager(PM); 1094 1095 if (VerifyOutput) 1096 PM.add(createVerifierPass()); 1097 PerformThinLTO = false; 1098 } 1099 1100 void PassManagerBuilder::populateLTOPassManager(legacy::PassManagerBase &PM) { 1101 if (LibraryInfo) 1102 PM.add(new TargetLibraryInfoWrapperPass(*LibraryInfo)); 1103 1104 if (VerifyInput) 1105 PM.add(createVerifierPass()); 1106 1107 addExtensionsToPM(EP_FullLinkTimeOptimizationEarly, PM); 1108 1109 if (OptLevel != 0) 1110 addLTOOptimizationPasses(PM); 1111 else { 1112 // The whole-program-devirt pass needs to run at -O0 because only it knows 1113 // about the llvm.type.checked.load intrinsic: it needs to both lower the 1114 // intrinsic itself and handle it in the summary. 1115 PM.add(createWholeProgramDevirtPass(ExportSummary, nullptr)); 1116 } 1117 1118 // Create a function that performs CFI checks for cross-DSO calls with targets 1119 // in the current module. 1120 PM.add(createCrossDSOCFIPass()); 1121 1122 // Lower type metadata and the type.test intrinsic. This pass supports Clang's 1123 // control flow integrity mechanisms (-fsanitize=cfi*) and needs to run at 1124 // link time if CFI is enabled. The pass does nothing if CFI is disabled. 1125 PM.add(createLowerTypeTestsPass(ExportSummary, nullptr)); 1126 1127 if (OptLevel != 0) 1128 addLateLTOOptimizationPasses(PM); 1129 1130 addExtensionsToPM(EP_FullLinkTimeOptimizationLast, PM); 1131 1132 if (VerifyOutput) 1133 PM.add(createVerifierPass()); 1134 } 1135 1136 LLVMPassManagerBuilderRef LLVMPassManagerBuilderCreate() { 1137 PassManagerBuilder *PMB = new PassManagerBuilder(); 1138 return wrap(PMB); 1139 } 1140 1141 void LLVMPassManagerBuilderDispose(LLVMPassManagerBuilderRef PMB) { 1142 PassManagerBuilder *Builder = unwrap(PMB); 1143 delete Builder; 1144 } 1145 1146 void 1147 LLVMPassManagerBuilderSetOptLevel(LLVMPassManagerBuilderRef PMB, 1148 unsigned OptLevel) { 1149 PassManagerBuilder *Builder = unwrap(PMB); 1150 Builder->OptLevel = OptLevel; 1151 } 1152 1153 void 1154 LLVMPassManagerBuilderSetSizeLevel(LLVMPassManagerBuilderRef PMB, 1155 unsigned SizeLevel) { 1156 PassManagerBuilder *Builder = unwrap(PMB); 1157 Builder->SizeLevel = SizeLevel; 1158 } 1159 1160 void 1161 LLVMPassManagerBuilderSetDisableUnitAtATime(LLVMPassManagerBuilderRef PMB, 1162 LLVMBool Value) { 1163 // NOTE: The DisableUnitAtATime switch has been removed. 1164 } 1165 1166 void 1167 LLVMPassManagerBuilderSetDisableUnrollLoops(LLVMPassManagerBuilderRef PMB, 1168 LLVMBool Value) { 1169 PassManagerBuilder *Builder = unwrap(PMB); 1170 Builder->DisableUnrollLoops = Value; 1171 } 1172 1173 void 1174 LLVMPassManagerBuilderSetDisableSimplifyLibCalls(LLVMPassManagerBuilderRef PMB, 1175 LLVMBool Value) { 1176 // NOTE: The simplify-libcalls pass has been removed. 1177 } 1178 1179 void 1180 LLVMPassManagerBuilderUseInlinerWithThreshold(LLVMPassManagerBuilderRef PMB, 1181 unsigned Threshold) { 1182 PassManagerBuilder *Builder = unwrap(PMB); 1183 Builder->Inliner = createFunctionInliningPass(Threshold); 1184 } 1185 1186 void 1187 LLVMPassManagerBuilderPopulateFunctionPassManager(LLVMPassManagerBuilderRef PMB, 1188 LLVMPassManagerRef PM) { 1189 PassManagerBuilder *Builder = unwrap(PMB); 1190 legacy::FunctionPassManager *FPM = unwrap<legacy::FunctionPassManager>(PM); 1191 Builder->populateFunctionPassManager(*FPM); 1192 } 1193 1194 void 1195 LLVMPassManagerBuilderPopulateModulePassManager(LLVMPassManagerBuilderRef PMB, 1196 LLVMPassManagerRef PM) { 1197 PassManagerBuilder *Builder = unwrap(PMB); 1198 legacy::PassManagerBase *MPM = unwrap(PM); 1199 Builder->populateModulePassManager(*MPM); 1200 } 1201 1202 void LLVMPassManagerBuilderPopulateLTOPassManager(LLVMPassManagerBuilderRef PMB, 1203 LLVMPassManagerRef PM, 1204 LLVMBool Internalize, 1205 LLVMBool RunInliner) { 1206 PassManagerBuilder *Builder = unwrap(PMB); 1207 legacy::PassManagerBase *LPM = unwrap(PM); 1208 1209 // A small backwards compatibility hack. populateLTOPassManager used to take 1210 // an RunInliner option. 1211 if (RunInliner && !Builder->Inliner) 1212 Builder->Inliner = createFunctionInliningPass(); 1213 1214 Builder->populateLTOPassManager(*LPM); 1215 } 1216