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