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