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