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