1 //===- Construction of pass pipelines -------------------------------------===// 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 /// \file 9 /// 10 /// This file provides the implementation of the PassBuilder based on our 11 /// static pass registry as well as related functionality. It also provides 12 /// helpers to aid in analyzing, debugging, and testing passes and pass 13 /// pipelines. 14 /// 15 //===----------------------------------------------------------------------===// 16 17 #include "llvm/Analysis/AliasAnalysis.h" 18 #include "llvm/Analysis/BasicAliasAnalysis.h" 19 #include "llvm/Analysis/CGSCCPassManager.h" 20 #include "llvm/Analysis/GlobalsModRef.h" 21 #include "llvm/Analysis/InlineAdvisor.h" 22 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 23 #include "llvm/Analysis/ProfileSummaryInfo.h" 24 #include "llvm/Analysis/ScopedNoAliasAA.h" 25 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 26 #include "llvm/IR/PassManager.h" 27 #include "llvm/Passes/OptimizationLevel.h" 28 #include "llvm/Passes/PassBuilder.h" 29 #include "llvm/Support/CommandLine.h" 30 #include "llvm/Support/ErrorHandling.h" 31 #include "llvm/Support/PGOOptions.h" 32 #include "llvm/Target/TargetMachine.h" 33 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 34 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 35 #include "llvm/Transforms/Coroutines/CoroEarly.h" 36 #include "llvm/Transforms/Coroutines/CoroElide.h" 37 #include "llvm/Transforms/Coroutines/CoroSplit.h" 38 #include "llvm/Transforms/IPO/AlwaysInliner.h" 39 #include "llvm/Transforms/IPO/Annotation2Metadata.h" 40 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 41 #include "llvm/Transforms/IPO/Attributor.h" 42 #include "llvm/Transforms/IPO/CalledValuePropagation.h" 43 #include "llvm/Transforms/IPO/ConstantMerge.h" 44 #include "llvm/Transforms/IPO/CrossDSOCFI.h" 45 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 46 #include "llvm/Transforms/IPO/ElimAvailExtern.h" 47 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 48 #include "llvm/Transforms/IPO/FunctionAttrs.h" 49 #include "llvm/Transforms/IPO/GlobalDCE.h" 50 #include "llvm/Transforms/IPO/GlobalOpt.h" 51 #include "llvm/Transforms/IPO/GlobalSplit.h" 52 #include "llvm/Transforms/IPO/HotColdSplitting.h" 53 #include "llvm/Transforms/IPO/IROutliner.h" 54 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 55 #include "llvm/Transforms/IPO/Inliner.h" 56 #include "llvm/Transforms/IPO/LowerTypeTests.h" 57 #include "llvm/Transforms/IPO/MergeFunctions.h" 58 #include "llvm/Transforms/IPO/ModuleInliner.h" 59 #include "llvm/Transforms/IPO/OpenMPOpt.h" 60 #include "llvm/Transforms/IPO/PartialInlining.h" 61 #include "llvm/Transforms/IPO/SCCP.h" 62 #include "llvm/Transforms/IPO/SampleProfile.h" 63 #include "llvm/Transforms/IPO/SampleProfileProbe.h" 64 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h" 65 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 66 #include "llvm/Transforms/InstCombine/InstCombine.h" 67 #include "llvm/Transforms/Instrumentation/CGProfile.h" 68 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" 69 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h" 70 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 71 #include "llvm/Transforms/Instrumentation/MemProfiler.h" 72 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 73 #include "llvm/Transforms/Scalar/ADCE.h" 74 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 75 #include "llvm/Transforms/Scalar/AnnotationRemarks.h" 76 #include "llvm/Transforms/Scalar/BDCE.h" 77 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 78 #include "llvm/Transforms/Scalar/ConstraintElimination.h" 79 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 80 #include "llvm/Transforms/Scalar/DFAJumpThreading.h" 81 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 82 #include "llvm/Transforms/Scalar/DivRemPairs.h" 83 #include "llvm/Transforms/Scalar/EarlyCSE.h" 84 #include "llvm/Transforms/Scalar/Float2Int.h" 85 #include "llvm/Transforms/Scalar/GVN.h" 86 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 87 #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 88 #include "llvm/Transforms/Scalar/JumpThreading.h" 89 #include "llvm/Transforms/Scalar/LICM.h" 90 #include "llvm/Transforms/Scalar/LoopDeletion.h" 91 #include "llvm/Transforms/Scalar/LoopDistribute.h" 92 #include "llvm/Transforms/Scalar/LoopFlatten.h" 93 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 94 #include "llvm/Transforms/Scalar/LoopInstSimplify.h" 95 #include "llvm/Transforms/Scalar/LoopInterchange.h" 96 #include "llvm/Transforms/Scalar/LoopLoadElimination.h" 97 #include "llvm/Transforms/Scalar/LoopPassManager.h" 98 #include "llvm/Transforms/Scalar/LoopRotation.h" 99 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 100 #include "llvm/Transforms/Scalar/LoopSink.h" 101 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h" 102 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 103 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h" 104 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 105 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 106 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 107 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 108 #include "llvm/Transforms/Scalar/NewGVN.h" 109 #include "llvm/Transforms/Scalar/Reassociate.h" 110 #include "llvm/Transforms/Scalar/SCCP.h" 111 #include "llvm/Transforms/Scalar/SROA.h" 112 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 113 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 114 #include "llvm/Transforms/Scalar/SpeculativeExecution.h" 115 #include "llvm/Transforms/Scalar/TailRecursionElimination.h" 116 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h" 117 #include "llvm/Transforms/Utils/AddDiscriminators.h" 118 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 119 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 120 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 121 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" 122 #include "llvm/Transforms/Utils/Mem2Reg.h" 123 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 124 #include "llvm/Transforms/Utils/RelLookupTableConverter.h" 125 #include "llvm/Transforms/Utils/SimplifyCFGOptions.h" 126 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 127 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 128 #include "llvm/Transforms/Vectorize/VectorCombine.h" 129 130 using namespace llvm; 131 132 static cl::opt<InliningAdvisorMode> UseInlineAdvisor( 133 "enable-ml-inliner", cl::init(InliningAdvisorMode::Default), cl::Hidden, 134 cl::desc("Enable ML policy for inliner. Currently trained for -Oz only"), 135 cl::values(clEnumValN(InliningAdvisorMode::Default, "default", 136 "Heuristics-based inliner version."), 137 clEnumValN(InliningAdvisorMode::Development, "development", 138 "Use development mode (runtime-loadable model)."), 139 clEnumValN(InliningAdvisorMode::Release, "release", 140 "Use release mode (AOT-compiled model)."))); 141 142 static cl::opt<bool> EnableSyntheticCounts( 143 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, 144 cl::desc("Run synthetic function entry count generation " 145 "pass")); 146 147 /// Flag to enable inline deferral during PGO. 148 static cl::opt<bool> 149 EnablePGOInlineDeferral("enable-npm-pgo-inline-deferral", cl::init(true), 150 cl::Hidden, 151 cl::desc("Enable inline deferral during PGO")); 152 153 static cl::opt<bool> EnableMemProfiler("enable-mem-prof", cl::init(false), 154 cl::Hidden, cl::ZeroOrMore, 155 cl::desc("Enable memory profiler")); 156 157 static cl::opt<bool> EnableModuleInliner("enable-module-inliner", 158 cl::init(false), cl::Hidden, 159 cl::desc("Enable module inliner")); 160 161 static cl::opt<bool> PerformMandatoryInliningsFirst( 162 "mandatory-inlining-first", cl::init(true), cl::Hidden, cl::ZeroOrMore, 163 cl::desc("Perform mandatory inlinings module-wide, before performing " 164 "inlining.")); 165 166 static cl::opt<bool> EnableO3NonTrivialUnswitching( 167 "enable-npm-O3-nontrivial-unswitch", cl::init(true), cl::Hidden, 168 cl::ZeroOrMore, cl::desc("Enable non-trivial loop unswitching for -O3")); 169 170 static cl::opt<bool> EnableEagerlyInvalidateAnalyses( 171 "eagerly-invalidate-analyses", cl::init(true), cl::Hidden, 172 cl::desc("Eagerly invalidate more analyses in default pipelines")); 173 174 static cl::opt<bool> EnableNoRerunSimplificationPipeline( 175 "enable-no-rerun-simplification-pipeline", cl::init(false), cl::Hidden, 176 cl::desc( 177 "Prevent running the simplification pipeline on a function more " 178 "than once in the case that SCC mutations cause a function to be " 179 "visited multiple times as long as the function has not been changed")); 180 181 static cl::opt<bool> EnableMergeFunctions( 182 "enable-merge-functions", cl::init(false), cl::Hidden, 183 cl::desc("Enable function merging as part of the optimization pipeline")); 184 185 PipelineTuningOptions::PipelineTuningOptions() { 186 LoopInterleaving = true; 187 LoopVectorization = true; 188 SLPVectorization = false; 189 LoopUnrolling = true; 190 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 191 LicmMssaOptCap = SetLicmMssaOptCap; 192 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 193 CallGraphProfile = true; 194 MergeFunctions = EnableMergeFunctions; 195 EagerlyInvalidateAnalyses = EnableEagerlyInvalidateAnalyses; 196 } 197 198 namespace llvm { 199 200 extern cl::opt<unsigned> MaxDevirtIterations; 201 extern cl::opt<bool> EnableConstraintElimination; 202 extern cl::opt<bool> EnableFunctionSpecialization; 203 extern cl::opt<bool> EnableGVNHoist; 204 extern cl::opt<bool> EnableGVNSink; 205 extern cl::opt<bool> EnableHotColdSplit; 206 extern cl::opt<bool> EnableIROutliner; 207 extern cl::opt<bool> EnableOrderFileInstrumentation; 208 extern cl::opt<bool> EnableCHR; 209 extern cl::opt<bool> EnableLoopInterchange; 210 extern cl::opt<bool> EnableUnrollAndJam; 211 extern cl::opt<bool> EnableLoopFlatten; 212 extern cl::opt<bool> EnableDFAJumpThreading; 213 extern cl::opt<bool> RunNewGVN; 214 extern cl::opt<bool> RunPartialInlining; 215 extern cl::opt<bool> ExtraVectorizerPasses; 216 217 extern cl::opt<bool> FlattenedProfileUsed; 218 219 extern cl::opt<AttributorRunOption> AttributorRun; 220 extern cl::opt<bool> EnableKnowledgeRetention; 221 222 extern cl::opt<bool> EnableMatrix; 223 224 extern cl::opt<bool> DisablePreInliner; 225 extern cl::opt<int> PreInlineThreshold; 226 } // namespace llvm 227 228 void PassBuilder::invokePeepholeEPCallbacks(FunctionPassManager &FPM, 229 OptimizationLevel Level) { 230 for (auto &C : PeepholeEPCallbacks) 231 C(FPM, Level); 232 } 233 234 // Helper to add AnnotationRemarksPass. 235 static void addAnnotationRemarksPass(ModulePassManager &MPM) { 236 FunctionPassManager FPM; 237 FPM.addPass(AnnotationRemarksPass()); 238 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 239 } 240 241 // Helper to check if the current compilation phase is preparing for LTO 242 static bool isLTOPreLink(ThinOrFullLTOPhase Phase) { 243 return Phase == ThinOrFullLTOPhase::ThinLTOPreLink || 244 Phase == ThinOrFullLTOPhase::FullLTOPreLink; 245 } 246 247 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 248 FunctionPassManager 249 PassBuilder::buildO1FunctionSimplificationPipeline(OptimizationLevel Level, 250 ThinOrFullLTOPhase Phase) { 251 252 FunctionPassManager FPM; 253 254 // Form SSA out of local memory accesses after breaking apart aggregates into 255 // scalars. 256 FPM.addPass(SROAPass()); 257 258 // Catch trivial redundancies 259 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 260 261 // Hoisting of scalars and load expressions. 262 FPM.addPass(SimplifyCFGPass()); 263 FPM.addPass(InstCombinePass()); 264 265 FPM.addPass(LibCallsShrinkWrapPass()); 266 267 invokePeepholeEPCallbacks(FPM, Level); 268 269 FPM.addPass(SimplifyCFGPass()); 270 271 // Form canonically associated expression trees, and simplify the trees using 272 // basic mathematical properties. For example, this will form (nearly) 273 // minimal multiplication trees. 274 FPM.addPass(ReassociatePass()); 275 276 // Add the primary loop simplification pipeline. 277 // FIXME: Currently this is split into two loop pass pipelines because we run 278 // some function passes in between them. These can and should be removed 279 // and/or replaced by scheduling the loop pass equivalents in the correct 280 // positions. But those equivalent passes aren't powerful enough yet. 281 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 282 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 283 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 284 // `LoopInstSimplify`. 285 LoopPassManager LPM1, LPM2; 286 287 // Simplify the loop body. We do this initially to clean up after other loop 288 // passes run, either when iterating on a loop or on inner loops with 289 // implications on the outer loop. 290 LPM1.addPass(LoopInstSimplifyPass()); 291 LPM1.addPass(LoopSimplifyCFGPass()); 292 293 // Try to remove as much code from the loop header as possible, 294 // to reduce amount of IR that will have to be duplicated. 295 // TODO: Investigate promotion cap for O1. 296 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 297 298 LPM1.addPass(LoopRotatePass(/* Disable header duplication */ true, 299 isLTOPreLink(Phase))); 300 // TODO: Investigate promotion cap for O1. 301 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 302 LPM1.addPass(SimpleLoopUnswitchPass()); 303 304 LPM2.addPass(LoopIdiomRecognizePass()); 305 LPM2.addPass(IndVarSimplifyPass()); 306 307 for (auto &C : LateLoopOptimizationsEPCallbacks) 308 C(LPM2, Level); 309 310 LPM2.addPass(LoopDeletionPass()); 311 312 if (EnableLoopInterchange) 313 LPM2.addPass(LoopInterchangePass()); 314 315 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 316 // because it changes IR to makes profile annotation in back compile 317 // inaccurate. The normal unroller doesn't pay attention to forced full unroll 318 // attributes so we need to make sure and allow the full unroll pass to pay 319 // attention to it. 320 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || 321 PGOOpt->Action != PGOOptions::SampleUse) 322 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 323 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 324 PTO.ForgetAllSCEVInLoopUnroll)); 325 326 for (auto &C : LoopOptimizerEndEPCallbacks) 327 C(LPM2, Level); 328 329 // We provide the opt remark emitter pass for LICM to use. We only need to do 330 // this once as it is immutable. 331 FPM.addPass( 332 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 333 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), 334 /*UseMemorySSA=*/true, 335 /*UseBlockFrequencyInfo=*/true)); 336 FPM.addPass(SimplifyCFGPass()); 337 FPM.addPass(InstCombinePass()); 338 if (EnableLoopFlatten) 339 FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); 340 // The loop passes in LPM2 (LoopFullUnrollPass) do not preserve MemorySSA. 341 // *All* loop passes must preserve it, in order to be able to use it. 342 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), 343 /*UseMemorySSA=*/false, 344 /*UseBlockFrequencyInfo=*/false)); 345 346 // Delete small array after loop unroll. 347 FPM.addPass(SROAPass()); 348 349 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 350 FPM.addPass(MemCpyOptPass()); 351 352 // Sparse conditional constant propagation. 353 // FIXME: It isn't clear why we do this *after* loop passes rather than 354 // before... 355 FPM.addPass(SCCPPass()); 356 357 // Delete dead bit computations (instcombine runs after to fold away the dead 358 // computations, and then ADCE will run later to exploit any new DCE 359 // opportunities that creates). 360 FPM.addPass(BDCEPass()); 361 362 // Run instcombine after redundancy and dead bit elimination to exploit 363 // opportunities opened up by them. 364 FPM.addPass(InstCombinePass()); 365 invokePeepholeEPCallbacks(FPM, Level); 366 367 FPM.addPass(CoroElidePass()); 368 369 for (auto &C : ScalarOptimizerLateEPCallbacks) 370 C(FPM, Level); 371 372 // Finally, do an expensive DCE pass to catch all the dead code exposed by 373 // the simplifications and basic cleanup after all the simplifications. 374 // TODO: Investigate if this is too expensive. 375 FPM.addPass(ADCEPass()); 376 FPM.addPass(SimplifyCFGPass()); 377 FPM.addPass(InstCombinePass()); 378 invokePeepholeEPCallbacks(FPM, Level); 379 380 return FPM; 381 } 382 383 FunctionPassManager 384 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, 385 ThinOrFullLTOPhase Phase) { 386 assert(Level != OptimizationLevel::O0 && "Must request optimizations!"); 387 388 // The O1 pipeline has a separate pipeline creation function to simplify 389 // construction readability. 390 if (Level.getSpeedupLevel() == 1) 391 return buildO1FunctionSimplificationPipeline(Level, Phase); 392 393 FunctionPassManager FPM; 394 395 // Form SSA out of local memory accesses after breaking apart aggregates into 396 // scalars. 397 FPM.addPass(SROAPass()); 398 399 // Catch trivial redundancies 400 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 401 if (EnableKnowledgeRetention) 402 FPM.addPass(AssumeSimplifyPass()); 403 404 // Hoisting of scalars and load expressions. 405 if (EnableGVNHoist) 406 FPM.addPass(GVNHoistPass()); 407 408 // Global value numbering based sinking. 409 if (EnableGVNSink) { 410 FPM.addPass(GVNSinkPass()); 411 FPM.addPass(SimplifyCFGPass()); 412 } 413 414 if (EnableConstraintElimination) 415 FPM.addPass(ConstraintEliminationPass()); 416 417 // Speculative execution if the target has divergent branches; otherwise nop. 418 FPM.addPass(SpeculativeExecutionPass(/* OnlyIfDivergentTarget =*/true)); 419 420 // Optimize based on known information about branches, and cleanup afterward. 421 FPM.addPass(JumpThreadingPass()); 422 FPM.addPass(CorrelatedValuePropagationPass()); 423 424 FPM.addPass(SimplifyCFGPass()); 425 FPM.addPass(InstCombinePass()); 426 if (Level == OptimizationLevel::O3) 427 FPM.addPass(AggressiveInstCombinePass()); 428 429 if (!Level.isOptimizingForSize()) 430 FPM.addPass(LibCallsShrinkWrapPass()); 431 432 invokePeepholeEPCallbacks(FPM, Level); 433 434 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy 435 // using the size value profile. Don't perform this when optimizing for size. 436 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse && 437 !Level.isOptimizingForSize()) 438 FPM.addPass(PGOMemOPSizeOpt()); 439 440 FPM.addPass(TailCallElimPass()); 441 FPM.addPass(SimplifyCFGPass()); 442 443 // Form canonically associated expression trees, and simplify the trees using 444 // basic mathematical properties. For example, this will form (nearly) 445 // minimal multiplication trees. 446 FPM.addPass(ReassociatePass()); 447 448 // Add the primary loop simplification pipeline. 449 // FIXME: Currently this is split into two loop pass pipelines because we run 450 // some function passes in between them. These can and should be removed 451 // and/or replaced by scheduling the loop pass equivalents in the correct 452 // positions. But those equivalent passes aren't powerful enough yet. 453 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 454 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 455 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 456 // `LoopInstSimplify`. 457 LoopPassManager LPM1, LPM2; 458 459 // Simplify the loop body. We do this initially to clean up after other loop 460 // passes run, either when iterating on a loop or on inner loops with 461 // implications on the outer loop. 462 LPM1.addPass(LoopInstSimplifyPass()); 463 LPM1.addPass(LoopSimplifyCFGPass()); 464 465 // Try to remove as much code from the loop header as possible, 466 // to reduce amount of IR that will have to be duplicated. 467 // TODO: Investigate promotion cap for O1. 468 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 469 470 // Disable header duplication in loop rotation at -Oz. 471 LPM1.addPass( 472 LoopRotatePass(Level != OptimizationLevel::Oz, isLTOPreLink(Phase))); 473 // TODO: Investigate promotion cap for O1. 474 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 475 LPM1.addPass( 476 SimpleLoopUnswitchPass(/* NonTrivial */ Level == OptimizationLevel::O3 && 477 EnableO3NonTrivialUnswitching)); 478 LPM2.addPass(LoopIdiomRecognizePass()); 479 LPM2.addPass(IndVarSimplifyPass()); 480 481 for (auto &C : LateLoopOptimizationsEPCallbacks) 482 C(LPM2, Level); 483 484 LPM2.addPass(LoopDeletionPass()); 485 486 if (EnableLoopInterchange) 487 LPM2.addPass(LoopInterchangePass()); 488 489 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 490 // because it changes IR to makes profile annotation in back compile 491 // inaccurate. The normal unroller doesn't pay attention to forced full unroll 492 // attributes so we need to make sure and allow the full unroll pass to pay 493 // attention to it. 494 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink || !PGOOpt || 495 PGOOpt->Action != PGOOptions::SampleUse) 496 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 497 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 498 PTO.ForgetAllSCEVInLoopUnroll)); 499 500 for (auto &C : LoopOptimizerEndEPCallbacks) 501 C(LPM2, Level); 502 503 // We provide the opt remark emitter pass for LICM to use. We only need to do 504 // this once as it is immutable. 505 FPM.addPass( 506 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 507 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), 508 /*UseMemorySSA=*/true, 509 /*UseBlockFrequencyInfo=*/true)); 510 FPM.addPass(SimplifyCFGPass()); 511 FPM.addPass(InstCombinePass()); 512 if (EnableLoopFlatten) 513 FPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); 514 // The loop passes in LPM2 (LoopIdiomRecognizePass, IndVarSimplifyPass, 515 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA. 516 // *All* loop passes must preserve it, in order to be able to use it. 517 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), 518 /*UseMemorySSA=*/false, 519 /*UseBlockFrequencyInfo=*/false)); 520 521 // Delete small array after loop unroll. 522 FPM.addPass(SROAPass()); 523 524 // The matrix extension can introduce large vector operations early, which can 525 // benefit from running vector-combine early on. 526 if (EnableMatrix) 527 FPM.addPass(VectorCombinePass(/*ScalarizationOnly=*/true)); 528 529 // Eliminate redundancies. 530 FPM.addPass(MergedLoadStoreMotionPass()); 531 if (RunNewGVN) 532 FPM.addPass(NewGVNPass()); 533 else 534 FPM.addPass(GVNPass()); 535 536 // Sparse conditional constant propagation. 537 // FIXME: It isn't clear why we do this *after* loop passes rather than 538 // before... 539 FPM.addPass(SCCPPass()); 540 541 // Delete dead bit computations (instcombine runs after to fold away the dead 542 // computations, and then ADCE will run later to exploit any new DCE 543 // opportunities that creates). 544 FPM.addPass(BDCEPass()); 545 546 // Run instcombine after redundancy and dead bit elimination to exploit 547 // opportunities opened up by them. 548 FPM.addPass(InstCombinePass()); 549 invokePeepholeEPCallbacks(FPM, Level); 550 551 // Re-consider control flow based optimizations after redundancy elimination, 552 // redo DCE, etc. 553 if (EnableDFAJumpThreading && Level.getSizeLevel() == 0) 554 FPM.addPass(DFAJumpThreadingPass()); 555 556 FPM.addPass(JumpThreadingPass()); 557 FPM.addPass(CorrelatedValuePropagationPass()); 558 559 // Finally, do an expensive DCE pass to catch all the dead code exposed by 560 // the simplifications and basic cleanup after all the simplifications. 561 // TODO: Investigate if this is too expensive. 562 FPM.addPass(ADCEPass()); 563 564 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 565 FPM.addPass(MemCpyOptPass()); 566 567 FPM.addPass(DSEPass()); 568 FPM.addPass(createFunctionToLoopPassAdaptor( 569 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 570 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 571 572 FPM.addPass(CoroElidePass()); 573 574 for (auto &C : ScalarOptimizerLateEPCallbacks) 575 C(FPM, Level); 576 577 FPM.addPass(SimplifyCFGPass( 578 SimplifyCFGOptions().hoistCommonInsts(true).sinkCommonInsts(true))); 579 FPM.addPass(InstCombinePass()); 580 invokePeepholeEPCallbacks(FPM, Level); 581 582 if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt && 583 (PGOOpt->Action == PGOOptions::IRUse || 584 PGOOpt->Action == PGOOptions::SampleUse)) 585 FPM.addPass(ControlHeightReductionPass()); 586 587 return FPM; 588 } 589 590 void PassBuilder::addRequiredLTOPreLinkPasses(ModulePassManager &MPM) { 591 MPM.addPass(CanonicalizeAliasesPass()); 592 MPM.addPass(NameAnonGlobalPass()); 593 } 594 595 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, 596 OptimizationLevel Level, bool RunProfileGen, 597 bool IsCS, std::string ProfileFile, 598 std::string ProfileRemappingFile) { 599 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!"); 600 if (!IsCS && !DisablePreInliner) { 601 InlineParams IP; 602 603 IP.DefaultThreshold = PreInlineThreshold; 604 605 // FIXME: The hint threshold has the same value used by the regular inliner 606 // when not optimzing for size. This should probably be lowered after 607 // performance testing. 608 // FIXME: this comment is cargo culted from the old pass manager, revisit). 609 IP.HintThreshold = Level.isOptimizingForSize() ? PreInlineThreshold : 325; 610 ModuleInlinerWrapperPass MIWP(IP); 611 CGSCCPassManager &CGPipeline = MIWP.getPM(); 612 613 FunctionPassManager FPM; 614 FPM.addPass(SROAPass()); 615 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies. 616 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks. 617 FPM.addPass(InstCombinePass()); // Combine silly sequences. 618 invokePeepholeEPCallbacks(FPM, Level); 619 620 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 621 std::move(FPM), PTO.EagerlyInvalidateAnalyses)); 622 623 MPM.addPass(std::move(MIWP)); 624 625 // Delete anything that is now dead to make sure that we don't instrument 626 // dead code. Instrumentation can end up keeping dead code around and 627 // dramatically increase code size. 628 MPM.addPass(GlobalDCEPass()); 629 } 630 631 if (!RunProfileGen) { 632 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 633 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 634 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 635 // RequireAnalysisPass for PSI before subsequent non-module passes. 636 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 637 return; 638 } 639 640 // Perform PGO instrumentation. 641 MPM.addPass(PGOInstrumentationGen(IsCS)); 642 643 FunctionPassManager FPM; 644 // Disable header duplication in loop rotation at -Oz. 645 FPM.addPass(createFunctionToLoopPassAdaptor( 646 LoopRotatePass(Level != OptimizationLevel::Oz), /*UseMemorySSA=*/false, 647 /*UseBlockFrequencyInfo=*/false)); 648 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM), 649 PTO.EagerlyInvalidateAnalyses)); 650 651 // Add the profile lowering pass. 652 InstrProfOptions Options; 653 if (!ProfileFile.empty()) 654 Options.InstrProfileOutput = ProfileFile; 655 // Do counter promotion at Level greater than O0. 656 Options.DoCounterPromotion = true; 657 Options.UseBFIInPromotion = IsCS; 658 MPM.addPass(InstrProfiling(Options, IsCS)); 659 } 660 661 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM, 662 bool RunProfileGen, bool IsCS, 663 std::string ProfileFile, 664 std::string ProfileRemappingFile) { 665 if (!RunProfileGen) { 666 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 667 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 668 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 669 // RequireAnalysisPass for PSI before subsequent non-module passes. 670 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 671 return; 672 } 673 674 // Perform PGO instrumentation. 675 MPM.addPass(PGOInstrumentationGen(IsCS)); 676 // Add the profile lowering pass. 677 InstrProfOptions Options; 678 if (!ProfileFile.empty()) 679 Options.InstrProfileOutput = ProfileFile; 680 // Do not do counter promotion at O0. 681 Options.DoCounterPromotion = false; 682 Options.UseBFIInPromotion = IsCS; 683 MPM.addPass(InstrProfiling(Options, IsCS)); 684 } 685 686 static InlineParams getInlineParamsFromOptLevel(OptimizationLevel Level) { 687 return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel()); 688 } 689 690 ModuleInlinerWrapperPass 691 PassBuilder::buildInlinerPipeline(OptimizationLevel Level, 692 ThinOrFullLTOPhase Phase) { 693 InlineParams IP = getInlineParamsFromOptLevel(Level); 694 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt && 695 PGOOpt->Action == PGOOptions::SampleUse) 696 IP.HotCallSiteThreshold = 0; 697 698 if (PGOOpt) 699 IP.EnableDeferral = EnablePGOInlineDeferral; 700 701 ModuleInlinerWrapperPass MIWP(IP, PerformMandatoryInliningsFirst, 702 UseInlineAdvisor, MaxDevirtIterations); 703 704 // Require the GlobalsAA analysis for the module so we can query it within 705 // the CGSCC pipeline. 706 MIWP.addModulePass(RequireAnalysisPass<GlobalsAA, Module>()); 707 // Invalidate AAManager so it can be recreated and pick up the newly available 708 // GlobalsAA. 709 MIWP.addModulePass( 710 createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>())); 711 712 // Require the ProfileSummaryAnalysis for the module so we can query it within 713 // the inliner pass. 714 MIWP.addModulePass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 715 716 // Now begin the main postorder CGSCC pipeline. 717 // FIXME: The current CGSCC pipeline has its origins in the legacy pass 718 // manager and trying to emulate its precise behavior. Much of this doesn't 719 // make a lot of sense and we should revisit the core CGSCC structure. 720 CGSCCPassManager &MainCGPipeline = MIWP.getPM(); 721 722 // Note: historically, the PruneEH pass was run first to deduce nounwind and 723 // generally clean up exception handling overhead. It isn't clear this is 724 // valuable as the inliner doesn't currently care whether it is inlining an 725 // invoke or a call. 726 727 if (AttributorRun & AttributorRunOption::CGSCC) 728 MainCGPipeline.addPass(AttributorCGSCCPass()); 729 730 // Now deduce any function attributes based in the current code. 731 MainCGPipeline.addPass(PostOrderFunctionAttrsPass()); 732 733 // When at O3 add argument promotion to the pass pipeline. 734 // FIXME: It isn't at all clear why this should be limited to O3. 735 if (Level == OptimizationLevel::O3) 736 MainCGPipeline.addPass(ArgumentPromotionPass()); 737 738 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 739 // there are no OpenMP runtime calls present in the module. 740 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3) 741 MainCGPipeline.addPass(OpenMPOptCGSCCPass()); 742 743 for (auto &C : CGSCCOptimizerLateEPCallbacks) 744 C(MainCGPipeline, Level); 745 746 // Lastly, add the core function simplification pipeline nested inside the 747 // CGSCC walk. 748 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 749 buildFunctionSimplificationPipeline(Level, Phase), 750 PTO.EagerlyInvalidateAnalyses, EnableNoRerunSimplificationPipeline)); 751 752 MainCGPipeline.addPass(CoroSplitPass(Level != OptimizationLevel::O0)); 753 754 if (EnableNoRerunSimplificationPipeline) 755 MIWP.addLateModulePass(createModuleToFunctionPassAdaptor( 756 InvalidateAnalysisPass<ShouldNotRunFunctionPassesAnalysis>())); 757 758 return MIWP; 759 } 760 761 ModulePassManager 762 PassBuilder::buildModuleInlinerPipeline(OptimizationLevel Level, 763 ThinOrFullLTOPhase Phase) { 764 ModulePassManager MPM; 765 766 InlineParams IP = getInlineParamsFromOptLevel(Level); 767 if (Phase == ThinOrFullLTOPhase::ThinLTOPreLink && PGOOpt && 768 PGOOpt->Action == PGOOptions::SampleUse) 769 IP.HotCallSiteThreshold = 0; 770 771 if (PGOOpt) 772 IP.EnableDeferral = EnablePGOInlineDeferral; 773 774 // The inline deferral logic is used to avoid losing some 775 // inlining chance in future. It is helpful in SCC inliner, in which 776 // inlining is processed in bottom-up order. 777 // While in module inliner, the inlining order is a priority-based order 778 // by default. The inline deferral is unnecessary there. So we disable the 779 // inline deferral logic in module inliner. 780 IP.EnableDeferral = false; 781 782 MPM.addPass(ModuleInlinerPass(IP, UseInlineAdvisor)); 783 784 MPM.addPass(createModuleToFunctionPassAdaptor( 785 buildFunctionSimplificationPipeline(Level, Phase), 786 PTO.EagerlyInvalidateAnalyses)); 787 788 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 789 CoroSplitPass(Level != OptimizationLevel::O0))); 790 791 return MPM; 792 } 793 794 ModulePassManager 795 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, 796 ThinOrFullLTOPhase Phase) { 797 ModulePassManager MPM; 798 799 // Place pseudo probe instrumentation as the first pass of the pipeline to 800 // minimize the impact of optimization changes. 801 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 802 Phase != ThinOrFullLTOPhase::ThinLTOPostLink) 803 MPM.addPass(SampleProfileProbePass(TM)); 804 805 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse); 806 807 // In ThinLTO mode, when flattened profile is used, all the available 808 // profile information will be annotated in PreLink phase so there is 809 // no need to load the profile again in PostLink. 810 bool LoadSampleProfile = 811 HasSampleProfile && 812 !(FlattenedProfileUsed && Phase == ThinOrFullLTOPhase::ThinLTOPostLink); 813 814 // During the ThinLTO backend phase we perform early indirect call promotion 815 // here, before globalopt. Otherwise imported available_externally functions 816 // look unreferenced and are removed. If we are going to load the sample 817 // profile then defer until later. 818 // TODO: See if we can move later and consolidate with the location where 819 // we perform ICP when we are loading a sample profile. 820 // TODO: We pass HasSampleProfile (whether there was a sample profile file 821 // passed to the compile) to the SamplePGO flag of ICP. This is used to 822 // determine whether the new direct calls are annotated with prof metadata. 823 // Ideally this should be determined from whether the IR is annotated with 824 // sample profile, and not whether the a sample profile was provided on the 825 // command line. E.g. for flattened profiles where we will not be reloading 826 // the sample profile in the ThinLTO backend, we ideally shouldn't have to 827 // provide the sample profile file. 828 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink && !LoadSampleProfile) 829 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile)); 830 831 // Do basic inference of function attributes from known properties of system 832 // libraries and other oracles. 833 MPM.addPass(InferFunctionAttrsPass()); 834 835 // Create an early function pass manager to cleanup the output of the 836 // frontend. 837 FunctionPassManager EarlyFPM; 838 // Lower llvm.expect to metadata before attempting transforms. 839 // Compare/branch metadata may alter the behavior of passes like SimplifyCFG. 840 EarlyFPM.addPass(LowerExpectIntrinsicPass()); 841 EarlyFPM.addPass(SimplifyCFGPass()); 842 EarlyFPM.addPass(SROAPass()); 843 EarlyFPM.addPass(EarlyCSEPass()); 844 EarlyFPM.addPass(CoroEarlyPass()); 845 if (Level == OptimizationLevel::O3) 846 EarlyFPM.addPass(CallSiteSplittingPass()); 847 848 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation 849 // to convert bitcast to direct calls so that they can be inlined during the 850 // profile annotation prepration step. 851 // More details about SamplePGO design can be found in: 852 // https://research.google.com/pubs/pub45290.html 853 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured. 854 if (LoadSampleProfile) 855 EarlyFPM.addPass(InstCombinePass()); 856 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM), 857 PTO.EagerlyInvalidateAnalyses)); 858 859 if (LoadSampleProfile) { 860 // Annotate sample profile right after early FPM to ensure freshness of 861 // the debug info. 862 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 863 PGOOpt->ProfileRemappingFile, Phase)); 864 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 865 // RequireAnalysisPass for PSI before subsequent non-module passes. 866 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 867 // Do not invoke ICP in the LTOPrelink phase as it makes it hard 868 // for the profile annotation to be accurate in the LTO backend. 869 if (Phase != ThinOrFullLTOPhase::ThinLTOPreLink && 870 Phase != ThinOrFullLTOPhase::FullLTOPreLink) 871 // We perform early indirect call promotion here, before globalopt. 872 // This is important for the ThinLTO backend phase because otherwise 873 // imported available_externally functions look unreferenced and are 874 // removed. 875 MPM.addPass( 876 PGOIndirectCallPromotion(true /* IsInLTO */, true /* SamplePGO */)); 877 } 878 879 // Try to perform OpenMP specific optimizations on the module. This is a 880 // (quick!) no-op if there are no OpenMP runtime calls present in the module. 881 if (Level != OptimizationLevel::O0) 882 MPM.addPass(OpenMPOptPass()); 883 884 if (AttributorRun & AttributorRunOption::MODULE) 885 MPM.addPass(AttributorPass()); 886 887 // Lower type metadata and the type.test intrinsic in the ThinLTO 888 // post link pipeline after ICP. This is to enable usage of the type 889 // tests in ICP sequences. 890 if (Phase == ThinOrFullLTOPhase::ThinLTOPostLink) 891 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 892 893 for (auto &C : PipelineEarlySimplificationEPCallbacks) 894 C(MPM, Level); 895 896 // Specialize functions with IPSCCP. 897 if (EnableFunctionSpecialization && Level == OptimizationLevel::O3) 898 MPM.addPass(FunctionSpecializationPass()); 899 900 // Interprocedural constant propagation now that basic cleanup has occurred 901 // and prior to optimizing globals. 902 // FIXME: This position in the pipeline hasn't been carefully considered in 903 // years, it should be re-analyzed. 904 MPM.addPass(IPSCCPPass()); 905 906 // Attach metadata to indirect call sites indicating the set of functions 907 // they may target at run-time. This should follow IPSCCP. 908 MPM.addPass(CalledValuePropagationPass()); 909 910 // Optimize globals to try and fold them into constants. 911 MPM.addPass(GlobalOptPass()); 912 913 // Promote any localized globals to SSA registers. 914 // FIXME: Should this instead by a run of SROA? 915 // FIXME: We should probably run instcombine and simplifycfg afterward to 916 // delete control flows that are dead once globals have been folded to 917 // constants. 918 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 919 920 // Remove any dead arguments exposed by cleanups and constant folding 921 // globals. 922 MPM.addPass(DeadArgumentEliminationPass()); 923 924 // Create a small function pass pipeline to cleanup after all the global 925 // optimizations. 926 FunctionPassManager GlobalCleanupPM; 927 GlobalCleanupPM.addPass(InstCombinePass()); 928 invokePeepholeEPCallbacks(GlobalCleanupPM, Level); 929 930 GlobalCleanupPM.addPass(SimplifyCFGPass()); 931 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM), 932 PTO.EagerlyInvalidateAnalyses)); 933 934 // Add all the requested passes for instrumentation PGO, if requested. 935 if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink && 936 (PGOOpt->Action == PGOOptions::IRInstr || 937 PGOOpt->Action == PGOOptions::IRUse)) { 938 addPGOInstrPasses(MPM, Level, 939 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr, 940 /* IsCS */ false, PGOOpt->ProfileFile, 941 PGOOpt->ProfileRemappingFile); 942 MPM.addPass(PGOIndirectCallPromotion(false, false)); 943 } 944 if (PGOOpt && Phase != ThinOrFullLTOPhase::ThinLTOPostLink && 945 PGOOpt->CSAction == PGOOptions::CSIRInstr) 946 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile)); 947 948 // Synthesize function entry counts for non-PGO compilation. 949 if (EnableSyntheticCounts && !PGOOpt) 950 MPM.addPass(SyntheticCountsPropagation()); 951 952 if (EnableModuleInliner) 953 MPM.addPass(buildModuleInlinerPipeline(Level, Phase)); 954 else 955 MPM.addPass(buildInlinerPipeline(Level, Phase)); 956 957 if (EnableMemProfiler && Phase != ThinOrFullLTOPhase::ThinLTOPreLink) { 958 MPM.addPass(createModuleToFunctionPassAdaptor(MemProfilerPass())); 959 MPM.addPass(ModuleMemProfilerPass()); 960 } 961 962 return MPM; 963 } 964 965 /// TODO: Should LTO cause any differences to this set of passes? 966 void PassBuilder::addVectorPasses(OptimizationLevel Level, 967 FunctionPassManager &FPM, bool IsFullLTO) { 968 FPM.addPass(LoopVectorizePass( 969 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization))); 970 971 if (IsFullLTO) { 972 // The vectorizer may have significantly shortened a loop body; unroll 973 // again. Unroll small loops to hide loop backedge latency and saturate any 974 // parallel execution resources of an out-of-order processor. We also then 975 // need to clean up redundancies and loop invariant code. 976 // FIXME: It would be really good to use a loop-integrated instruction 977 // combiner for cleanup here so that the unrolling and LICM can be pipelined 978 // across the loop nests. 979 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 980 if (EnableUnrollAndJam && PTO.LoopUnrolling) 981 FPM.addPass(createFunctionToLoopPassAdaptor( 982 LoopUnrollAndJamPass(Level.getSpeedupLevel()))); 983 FPM.addPass(LoopUnrollPass(LoopUnrollOptions( 984 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 985 PTO.ForgetAllSCEVInLoopUnroll))); 986 FPM.addPass(WarnMissedTransformationsPass()); 987 } 988 989 if (!IsFullLTO) { 990 // Eliminate loads by forwarding stores from the previous iteration to loads 991 // of the current iteration. 992 FPM.addPass(LoopLoadEliminationPass()); 993 } 994 // Cleanup after the loop optimization passes. 995 FPM.addPass(InstCombinePass()); 996 997 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) { 998 // At higher optimization levels, try to clean up any runtime overlap and 999 // alignment checks inserted by the vectorizer. We want to track correlated 1000 // runtime checks for two inner loops in the same outer loop, fold any 1001 // common computations, hoist loop-invariant aspects out of any outer loop, 1002 // and unswitch the runtime checks if possible. Once hoisted, we may have 1003 // dead (or speculatable) control flows or more combining opportunities. 1004 FPM.addPass(EarlyCSEPass()); 1005 FPM.addPass(CorrelatedValuePropagationPass()); 1006 FPM.addPass(InstCombinePass()); 1007 LoopPassManager LPM; 1008 LPM.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 1009 LPM.addPass(SimpleLoopUnswitchPass(/* NonTrivial */ Level == 1010 OptimizationLevel::O3)); 1011 FPM.addPass( 1012 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1013 FPM.addPass( 1014 createFunctionToLoopPassAdaptor(std::move(LPM), /*UseMemorySSA=*/true, 1015 /*UseBlockFrequencyInfo=*/true)); 1016 FPM.addPass(SimplifyCFGPass()); 1017 FPM.addPass(InstCombinePass()); 1018 } 1019 1020 // Now that we've formed fast to execute loop structures, we do further 1021 // optimizations. These are run afterward as they might block doing complex 1022 // analyses and transforms such as what are needed for loop vectorization. 1023 1024 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 1025 // GVN, loop transforms, and others have already run, so it's now better to 1026 // convert to more optimized IR using more aggressive simplify CFG options. 1027 // The extra sinking transform can create larger basic blocks, so do this 1028 // before SLP vectorization. 1029 FPM.addPass(SimplifyCFGPass(SimplifyCFGOptions() 1030 .forwardSwitchCondToPhi(true) 1031 .convertSwitchToLookupTable(true) 1032 .needCanonicalLoops(false) 1033 .hoistCommonInsts(true) 1034 .sinkCommonInsts(true))); 1035 1036 if (IsFullLTO) { 1037 FPM.addPass(SCCPPass()); 1038 FPM.addPass(InstCombinePass()); 1039 FPM.addPass(BDCEPass()); 1040 } 1041 1042 // Optimize parallel scalar instruction chains into SIMD instructions. 1043 if (PTO.SLPVectorization) { 1044 FPM.addPass(SLPVectorizerPass()); 1045 if (Level.getSpeedupLevel() > 1 && ExtraVectorizerPasses) { 1046 FPM.addPass(EarlyCSEPass()); 1047 } 1048 } 1049 // Enhance/cleanup vector code. 1050 FPM.addPass(VectorCombinePass()); 1051 1052 if (!IsFullLTO) { 1053 FPM.addPass(InstCombinePass()); 1054 // Unroll small loops to hide loop backedge latency and saturate any 1055 // parallel execution resources of an out-of-order processor. We also then 1056 // need to clean up redundancies and loop invariant code. 1057 // FIXME: It would be really good to use a loop-integrated instruction 1058 // combiner for cleanup here so that the unrolling and LICM can be pipelined 1059 // across the loop nests. 1060 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 1061 if (EnableUnrollAndJam && PTO.LoopUnrolling) { 1062 FPM.addPass(createFunctionToLoopPassAdaptor( 1063 LoopUnrollAndJamPass(Level.getSpeedupLevel()))); 1064 } 1065 FPM.addPass(LoopUnrollPass(LoopUnrollOptions( 1066 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 1067 PTO.ForgetAllSCEVInLoopUnroll))); 1068 FPM.addPass(WarnMissedTransformationsPass()); 1069 FPM.addPass(InstCombinePass()); 1070 FPM.addPass( 1071 RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1072 FPM.addPass(createFunctionToLoopPassAdaptor( 1073 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 1074 /*UseMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 1075 } 1076 1077 // Now that we've vectorized and unrolled loops, we may have more refined 1078 // alignment information, try to re-derive it here. 1079 FPM.addPass(AlignmentFromAssumptionsPass()); 1080 1081 if (IsFullLTO) 1082 FPM.addPass(InstCombinePass()); 1083 } 1084 1085 ModulePassManager 1086 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level, 1087 bool LTOPreLink) { 1088 ModulePassManager MPM; 1089 1090 // Optimize globals now that the module is fully simplified. 1091 MPM.addPass(GlobalOptPass()); 1092 MPM.addPass(GlobalDCEPass()); 1093 1094 // Run partial inlining pass to partially inline functions that have 1095 // large bodies. 1096 if (RunPartialInlining) 1097 MPM.addPass(PartialInlinerPass()); 1098 1099 // Remove avail extern fns and globals definitions since we aren't compiling 1100 // an object file for later LTO. For LTO we want to preserve these so they 1101 // are eligible for inlining at link-time. Note if they are unreferenced they 1102 // will be removed by GlobalDCE later, so this only impacts referenced 1103 // available externally globals. Eventually they will be suppressed during 1104 // codegen, but eliminating here enables more opportunity for GlobalDCE as it 1105 // may make globals referenced by available external functions dead and saves 1106 // running remaining passes on the eliminated functions. These should be 1107 // preserved during prelinking for link-time inlining decisions. 1108 if (!LTOPreLink) 1109 MPM.addPass(EliminateAvailableExternallyPass()); 1110 1111 if (EnableOrderFileInstrumentation) 1112 MPM.addPass(InstrOrderFilePass()); 1113 1114 // Do RPO function attribute inference across the module to forward-propagate 1115 // attributes where applicable. 1116 // FIXME: Is this really an optimization rather than a canonicalization? 1117 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1118 1119 // Do a post inline PGO instrumentation and use pass. This is a context 1120 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as 1121 // cross-module inline has not been done yet. The context sensitive 1122 // instrumentation is after all the inlines are done. 1123 if (!LTOPreLink && PGOOpt) { 1124 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1125 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, 1126 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1127 PGOOpt->ProfileRemappingFile); 1128 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1129 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false, 1130 /* IsCS */ true, PGOOpt->ProfileFile, 1131 PGOOpt->ProfileRemappingFile); 1132 } 1133 1134 // Re-require GloblasAA here prior to function passes. This is particularly 1135 // useful as the above will have inlined, DCE'ed, and function-attr 1136 // propagated everything. We should at this point have a reasonably minimal 1137 // and richly annotated call graph. By computing aliasing and mod/ref 1138 // information for all local globals here, the late loop passes and notably 1139 // the vectorizer will be able to use them to help recognize vectorizable 1140 // memory operations. 1141 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 1142 1143 FunctionPassManager OptimizePM; 1144 OptimizePM.addPass(Float2IntPass()); 1145 OptimizePM.addPass(LowerConstantIntrinsicsPass()); 1146 1147 if (EnableMatrix) { 1148 OptimizePM.addPass(LowerMatrixIntrinsicsPass()); 1149 OptimizePM.addPass(EarlyCSEPass()); 1150 } 1151 1152 // FIXME: We need to run some loop optimizations to re-rotate loops after 1153 // simplifycfg and others undo their rotation. 1154 1155 // Optimize the loop execution. These passes operate on entire loop nests 1156 // rather than on each loop in an inside-out manner, and so they are actually 1157 // function passes. 1158 1159 for (auto &C : VectorizerStartEPCallbacks) 1160 C(OptimizePM, Level); 1161 1162 LoopPassManager LPM; 1163 // First rotate loops that may have been un-rotated by prior passes. 1164 // Disable header duplication at -Oz. 1165 LPM.addPass(LoopRotatePass(Level != OptimizationLevel::Oz, LTOPreLink)); 1166 // Some loops may have become dead by now. Try to delete them. 1167 // FIXME: see discussion in https://reviews.llvm.org/D112851, 1168 // this may need to be revisited once we run GVN before loop deletion 1169 // in the simplification pipeline. 1170 LPM.addPass(LoopDeletionPass()); 1171 OptimizePM.addPass(createFunctionToLoopPassAdaptor( 1172 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/false)); 1173 1174 // Distribute loops to allow partial vectorization. I.e. isolate dependences 1175 // into separate loop that would otherwise inhibit vectorization. This is 1176 // currently only performed for loops marked with the metadata 1177 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 1178 OptimizePM.addPass(LoopDistributePass()); 1179 1180 // Populates the VFABI attribute with the scalar-to-vector mappings 1181 // from the TargetLibraryInfo. 1182 OptimizePM.addPass(InjectTLIMappings()); 1183 1184 addVectorPasses(Level, OptimizePM, /* IsFullLTO */ false); 1185 1186 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 1187 // canonicalization pass that enables other optimizations. As a result, 1188 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 1189 // result too early. 1190 OptimizePM.addPass(LoopSinkPass()); 1191 1192 // And finally clean up LCSSA form before generating code. 1193 OptimizePM.addPass(InstSimplifyPass()); 1194 1195 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 1196 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 1197 // flattening of blocks. 1198 OptimizePM.addPass(DivRemPairsPass()); 1199 1200 // LoopSink (and other loop passes since the last simplifyCFG) might have 1201 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 1202 OptimizePM.addPass(SimplifyCFGPass()); 1203 1204 OptimizePM.addPass(CoroCleanupPass()); 1205 1206 // Add the core optimizing pipeline. 1207 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM), 1208 PTO.EagerlyInvalidateAnalyses)); 1209 1210 for (auto &C : OptimizerLastEPCallbacks) 1211 C(MPM, Level); 1212 1213 // Split out cold code. Splitting is done late to avoid hiding context from 1214 // other optimizations and inadvertently regressing performance. The tradeoff 1215 // is that this has a higher code size cost than splitting early. 1216 if (EnableHotColdSplit && !LTOPreLink) 1217 MPM.addPass(HotColdSplittingPass()); 1218 1219 // Search the code for similar regions of code. If enough similar regions can 1220 // be found where extracting the regions into their own function will decrease 1221 // the size of the program, we extract the regions, a deduplicate the 1222 // structurally similar regions. 1223 if (EnableIROutliner) 1224 MPM.addPass(IROutlinerPass()); 1225 1226 // Merge functions if requested. 1227 if (PTO.MergeFunctions) 1228 MPM.addPass(MergeFunctionsPass()); 1229 1230 if (PTO.CallGraphProfile) 1231 MPM.addPass(CGProfilePass()); 1232 1233 // Now we need to do some global optimization transforms. 1234 // FIXME: It would seem like these should come first in the optimization 1235 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird 1236 // ordering here. 1237 MPM.addPass(GlobalDCEPass()); 1238 MPM.addPass(ConstantMergePass()); 1239 1240 // TODO: Relative look table converter pass caused an issue when full lto is 1241 // enabled. See https://reviews.llvm.org/D94355 for more details. 1242 // Until the issue fixed, disable this pass during pre-linking phase. 1243 if (!LTOPreLink) 1244 MPM.addPass(RelLookupTableConverterPass()); 1245 1246 return MPM; 1247 } 1248 1249 ModulePassManager 1250 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level, 1251 bool LTOPreLink) { 1252 assert(Level != OptimizationLevel::O0 && 1253 "Must request optimizations for the default pipeline!"); 1254 1255 ModulePassManager MPM; 1256 1257 // Convert @llvm.global.annotations to !annotation metadata. 1258 MPM.addPass(Annotation2MetadataPass()); 1259 1260 // Force any function attributes we want the rest of the pipeline to observe. 1261 MPM.addPass(ForceFunctionAttrsPass()); 1262 1263 // Apply module pipeline start EP callback. 1264 for (auto &C : PipelineStartEPCallbacks) 1265 C(MPM, Level); 1266 1267 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1268 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1269 1270 // Add the core simplification pipeline. 1271 MPM.addPass(buildModuleSimplificationPipeline( 1272 Level, LTOPreLink ? ThinOrFullLTOPhase::FullLTOPreLink 1273 : ThinOrFullLTOPhase::None)); 1274 1275 // Now add the optimization pipeline. 1276 MPM.addPass(buildModuleOptimizationPipeline(Level, LTOPreLink)); 1277 1278 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 1279 PGOOpt->Action == PGOOptions::SampleUse) 1280 MPM.addPass(PseudoProbeUpdatePass()); 1281 1282 // Emit annotation remarks. 1283 addAnnotationRemarksPass(MPM); 1284 1285 if (LTOPreLink) 1286 addRequiredLTOPreLinkPasses(MPM); 1287 1288 return MPM; 1289 } 1290 1291 ModulePassManager 1292 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level) { 1293 assert(Level != OptimizationLevel::O0 && 1294 "Must request optimizations for the default pipeline!"); 1295 1296 ModulePassManager MPM; 1297 1298 // Convert @llvm.global.annotations to !annotation metadata. 1299 MPM.addPass(Annotation2MetadataPass()); 1300 1301 // Force any function attributes we want the rest of the pipeline to observe. 1302 MPM.addPass(ForceFunctionAttrsPass()); 1303 1304 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1305 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1306 1307 // Apply module pipeline start EP callback. 1308 for (auto &C : PipelineStartEPCallbacks) 1309 C(MPM, Level); 1310 1311 // If we are planning to perform ThinLTO later, we don't bloat the code with 1312 // unrolling/vectorization/... now. Just simplify the module as much as we 1313 // can. 1314 MPM.addPass(buildModuleSimplificationPipeline( 1315 Level, ThinOrFullLTOPhase::ThinLTOPreLink)); 1316 1317 // Run partial inlining pass to partially inline functions that have 1318 // large bodies. 1319 // FIXME: It isn't clear whether this is really the right place to run this 1320 // in ThinLTO. Because there is another canonicalization and simplification 1321 // phase that will run after the thin link, running this here ends up with 1322 // less information than will be available later and it may grow functions in 1323 // ways that aren't beneficial. 1324 if (RunPartialInlining) 1325 MPM.addPass(PartialInlinerPass()); 1326 1327 // Reduce the size of the IR as much as possible. 1328 MPM.addPass(GlobalOptPass()); 1329 1330 // Module simplification splits coroutines, but does not fully clean up 1331 // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up 1332 // on these, we schedule the cleanup here. 1333 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1334 1335 if (PGOOpt && PGOOpt->PseudoProbeForProfiling && 1336 PGOOpt->Action == PGOOptions::SampleUse) 1337 MPM.addPass(PseudoProbeUpdatePass()); 1338 1339 // Handle OptimizerLastEPCallbacks added by clang on PreLink. Actual 1340 // optimization is going to be done in PostLink stage, but clang can't 1341 // add callbacks there in case of in-process ThinLTO called by linker. 1342 for (auto &C : OptimizerLastEPCallbacks) 1343 C(MPM, Level); 1344 1345 // Emit annotation remarks. 1346 addAnnotationRemarksPass(MPM); 1347 1348 addRequiredLTOPreLinkPasses(MPM); 1349 1350 return MPM; 1351 } 1352 1353 ModulePassManager PassBuilder::buildThinLTODefaultPipeline( 1354 OptimizationLevel Level, const ModuleSummaryIndex *ImportSummary) { 1355 ModulePassManager MPM; 1356 1357 // Convert @llvm.global.annotations to !annotation metadata. 1358 MPM.addPass(Annotation2MetadataPass()); 1359 1360 if (ImportSummary) { 1361 // These passes import type identifier resolutions for whole-program 1362 // devirtualization and CFI. They must run early because other passes may 1363 // disturb the specific instruction patterns that these passes look for, 1364 // creating dependencies on resolutions that may not appear in the summary. 1365 // 1366 // For example, GVN may transform the pattern assume(type.test) appearing in 1367 // two basic blocks into assume(phi(type.test, type.test)), which would 1368 // transform a dependency on a WPD resolution into a dependency on a type 1369 // identifier resolution for CFI. 1370 // 1371 // Also, WPD has access to more precise information than ICP and can 1372 // devirtualize more effectively, so it should operate on the IR first. 1373 // 1374 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1375 // metadata and intrinsics. 1376 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary)); 1377 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary)); 1378 } 1379 1380 if (Level == OptimizationLevel::O0) { 1381 // Run a second time to clean up any type tests left behind by WPD for use 1382 // in ICP. 1383 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1384 // Drop available_externally and unreferenced globals. This is necessary 1385 // with ThinLTO in order to avoid leaving undefined references to dead 1386 // globals in the object file. 1387 MPM.addPass(EliminateAvailableExternallyPass()); 1388 MPM.addPass(GlobalDCEPass()); 1389 return MPM; 1390 } 1391 1392 // Force any function attributes we want the rest of the pipeline to observe. 1393 MPM.addPass(ForceFunctionAttrsPass()); 1394 1395 // Add the core simplification pipeline. 1396 MPM.addPass(buildModuleSimplificationPipeline( 1397 Level, ThinOrFullLTOPhase::ThinLTOPostLink)); 1398 1399 // Now add the optimization pipeline. 1400 MPM.addPass(buildModuleOptimizationPipeline(Level)); 1401 1402 // Emit annotation remarks. 1403 addAnnotationRemarksPass(MPM); 1404 1405 return MPM; 1406 } 1407 1408 ModulePassManager 1409 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level) { 1410 assert(Level != OptimizationLevel::O0 && 1411 "Must request optimizations for the default pipeline!"); 1412 // FIXME: We should use a customized pre-link pipeline! 1413 return buildPerModuleDefaultPipeline(Level, 1414 /* LTOPreLink */ true); 1415 } 1416 1417 ModulePassManager 1418 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, 1419 ModuleSummaryIndex *ExportSummary) { 1420 ModulePassManager MPM; 1421 1422 // Convert @llvm.global.annotations to !annotation metadata. 1423 MPM.addPass(Annotation2MetadataPass()); 1424 1425 // Create a function that performs CFI checks for cross-DSO calls with targets 1426 // in the current module. 1427 MPM.addPass(CrossDSOCFIPass()); 1428 1429 if (Level == OptimizationLevel::O0) { 1430 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1431 // metadata and intrinsics. 1432 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1433 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1434 // Run a second time to clean up any type tests left behind by WPD for use 1435 // in ICP. 1436 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1437 1438 // Emit annotation remarks. 1439 addAnnotationRemarksPass(MPM); 1440 1441 return MPM; 1442 } 1443 1444 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) { 1445 // Load sample profile before running the LTO optimization pipeline. 1446 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 1447 PGOOpt->ProfileRemappingFile, 1448 ThinOrFullLTOPhase::FullLTOPostLink)); 1449 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 1450 // RequireAnalysisPass for PSI before subsequent non-module passes. 1451 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 1452 } 1453 1454 // Remove unused virtual tables to improve the quality of code generated by 1455 // whole-program devirtualization and bitset lowering. 1456 MPM.addPass(GlobalDCEPass()); 1457 1458 // Force any function attributes we want the rest of the pipeline to observe. 1459 MPM.addPass(ForceFunctionAttrsPass()); 1460 1461 // Do basic inference of function attributes from known properties of system 1462 // libraries and other oracles. 1463 MPM.addPass(InferFunctionAttrsPass()); 1464 1465 if (Level.getSpeedupLevel() > 1) { 1466 FunctionPassManager EarlyFPM; 1467 EarlyFPM.addPass(CallSiteSplittingPass()); 1468 MPM.addPass(createModuleToFunctionPassAdaptor( 1469 std::move(EarlyFPM), PTO.EagerlyInvalidateAnalyses)); 1470 1471 // Indirect call promotion. This should promote all the targets that are 1472 // left by the earlier promotion pass that promotes intra-module targets. 1473 // This two-step promotion is to save the compile time. For LTO, it should 1474 // produce the same result as if we only do promotion here. 1475 MPM.addPass(PGOIndirectCallPromotion( 1476 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)); 1477 1478 if (EnableFunctionSpecialization && Level == OptimizationLevel::O3) 1479 MPM.addPass(FunctionSpecializationPass()); 1480 // Propagate constants at call sites into the functions they call. This 1481 // opens opportunities for globalopt (and inlining) by substituting function 1482 // pointers passed as arguments to direct uses of functions. 1483 MPM.addPass(IPSCCPPass()); 1484 1485 // Attach metadata to indirect call sites indicating the set of functions 1486 // they may target at run-time. This should follow IPSCCP. 1487 MPM.addPass(CalledValuePropagationPass()); 1488 } 1489 1490 // Now deduce any function attributes based in the current code. 1491 MPM.addPass( 1492 createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass())); 1493 1494 // Do RPO function attribute inference across the module to forward-propagate 1495 // attributes where applicable. 1496 // FIXME: Is this really an optimization rather than a canonicalization? 1497 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1498 1499 // Use in-range annotations on GEP indices to split globals where beneficial. 1500 MPM.addPass(GlobalSplitPass()); 1501 1502 // Run whole program optimization of virtual call when the list of callees 1503 // is fixed. 1504 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1505 1506 // Stop here at -O1. 1507 if (Level == OptimizationLevel::O1) { 1508 // The LowerTypeTestsPass needs to run to lower type metadata and the 1509 // type.test intrinsics. The pass does nothing if CFI is disabled. 1510 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1511 // Run a second time to clean up any type tests left behind by WPD for use 1512 // in ICP (which is performed earlier than this in the regular LTO 1513 // pipeline). 1514 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1515 1516 // Emit annotation remarks. 1517 addAnnotationRemarksPass(MPM); 1518 1519 return MPM; 1520 } 1521 1522 // Optimize globals to try and fold them into constants. 1523 MPM.addPass(GlobalOptPass()); 1524 1525 // Promote any localized globals to SSA registers. 1526 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 1527 1528 // Linking modules together can lead to duplicate global constant, only 1529 // keep one copy of each constant. 1530 MPM.addPass(ConstantMergePass()); 1531 1532 // Remove unused arguments from functions. 1533 MPM.addPass(DeadArgumentEliminationPass()); 1534 1535 // Reduce the code after globalopt and ipsccp. Both can open up significant 1536 // simplification opportunities, and both can propagate functions through 1537 // function pointers. When this happens, we often have to resolve varargs 1538 // calls, etc, so let instcombine do this. 1539 FunctionPassManager PeepholeFPM; 1540 PeepholeFPM.addPass(InstCombinePass()); 1541 if (Level == OptimizationLevel::O3) 1542 PeepholeFPM.addPass(AggressiveInstCombinePass()); 1543 invokePeepholeEPCallbacks(PeepholeFPM, Level); 1544 1545 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM), 1546 PTO.EagerlyInvalidateAnalyses)); 1547 1548 // Note: historically, the PruneEH pass was run first to deduce nounwind and 1549 // generally clean up exception handling overhead. It isn't clear this is 1550 // valuable as the inliner doesn't currently care whether it is inlining an 1551 // invoke or a call. 1552 // Run the inliner now. 1553 MPM.addPass(ModuleInlinerWrapperPass(getInlineParamsFromOptLevel(Level))); 1554 1555 // Optimize globals again after we ran the inliner. 1556 MPM.addPass(GlobalOptPass()); 1557 1558 // Garbage collect dead functions. 1559 MPM.addPass(GlobalDCEPass()); 1560 1561 // If we didn't decide to inline a function, check to see if we can 1562 // transform it to pass arguments by value instead of by reference. 1563 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(ArgumentPromotionPass())); 1564 1565 FunctionPassManager FPM; 1566 // The IPO Passes may leave cruft around. Clean up after them. 1567 FPM.addPass(InstCombinePass()); 1568 invokePeepholeEPCallbacks(FPM, Level); 1569 1570 FPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true)); 1571 1572 // Do a post inline PGO instrumentation and use pass. This is a context 1573 // sensitive PGO pass. 1574 if (PGOOpt) { 1575 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1576 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ true, 1577 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1578 PGOOpt->ProfileRemappingFile); 1579 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1580 addPGOInstrPasses(MPM, Level, /* RunProfileGen */ false, 1581 /* IsCS */ true, PGOOpt->ProfileFile, 1582 PGOOpt->ProfileRemappingFile); 1583 } 1584 1585 // Break up allocas 1586 FPM.addPass(SROAPass()); 1587 1588 // LTO provides additional opportunities for tailcall elimination due to 1589 // link-time inlining, and visibility of nocapture attribute. 1590 FPM.addPass(TailCallElimPass()); 1591 1592 // Run a few AA driver optimizations here and now to cleanup the code. 1593 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM), 1594 PTO.EagerlyInvalidateAnalyses)); 1595 1596 MPM.addPass( 1597 createModuleToPostOrderCGSCCPassAdaptor(PostOrderFunctionAttrsPass())); 1598 1599 // Require the GlobalsAA analysis for the module so we can query it within 1600 // MainFPM. 1601 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 1602 // Invalidate AAManager so it can be recreated and pick up the newly available 1603 // GlobalsAA. 1604 MPM.addPass( 1605 createModuleToFunctionPassAdaptor(InvalidateAnalysisPass<AAManager>())); 1606 1607 FunctionPassManager MainFPM; 1608 MainFPM.addPass(createFunctionToLoopPassAdaptor( 1609 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 1610 /*USeMemorySSA=*/true, /*UseBlockFrequencyInfo=*/true)); 1611 1612 if (RunNewGVN) 1613 MainFPM.addPass(NewGVNPass()); 1614 else 1615 MainFPM.addPass(GVNPass()); 1616 1617 // Remove dead memcpy()'s. 1618 MainFPM.addPass(MemCpyOptPass()); 1619 1620 // Nuke dead stores. 1621 MainFPM.addPass(DSEPass()); 1622 MainFPM.addPass(MergedLoadStoreMotionPass()); 1623 1624 // More loops are countable; try to optimize them. 1625 if (EnableLoopFlatten && Level.getSpeedupLevel() > 1) 1626 MainFPM.addPass(createFunctionToLoopPassAdaptor(LoopFlattenPass())); 1627 1628 if (EnableConstraintElimination) 1629 MainFPM.addPass(ConstraintEliminationPass()); 1630 1631 LoopPassManager LPM; 1632 LPM.addPass(IndVarSimplifyPass()); 1633 LPM.addPass(LoopDeletionPass()); 1634 // FIXME: Add loop interchange. 1635 1636 // Unroll small loops and perform peeling. 1637 LPM.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 1638 /* OnlyWhenForced= */ !PTO.LoopUnrolling, 1639 PTO.ForgetAllSCEVInLoopUnroll)); 1640 // The loop passes in LPM (LoopFullUnrollPass) do not preserve MemorySSA. 1641 // *All* loop passes must preserve it, in order to be able to use it. 1642 MainFPM.addPass(createFunctionToLoopPassAdaptor( 1643 std::move(LPM), /*UseMemorySSA=*/false, /*UseBlockFrequencyInfo=*/true)); 1644 1645 MainFPM.addPass(LoopDistributePass()); 1646 1647 addVectorPasses(Level, MainFPM, /* IsFullLTO */ true); 1648 1649 invokePeepholeEPCallbacks(MainFPM, Level); 1650 MainFPM.addPass(JumpThreadingPass(/*InsertFreezeWhenUnfoldingSelect*/ true)); 1651 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM), 1652 PTO.EagerlyInvalidateAnalyses)); 1653 1654 // Lower type metadata and the type.test intrinsic. This pass supports 1655 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs 1656 // to be run at link time if CFI is enabled. This pass does nothing if 1657 // CFI is disabled. 1658 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1659 // Run a second time to clean up any type tests left behind by WPD for use 1660 // in ICP (which is performed earlier than this in the regular LTO pipeline). 1661 MPM.addPass(LowerTypeTestsPass(nullptr, nullptr, true)); 1662 1663 // Enable splitting late in the FullLTO post-link pipeline. This is done in 1664 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses). 1665 if (EnableHotColdSplit) 1666 MPM.addPass(HotColdSplittingPass()); 1667 1668 // Add late LTO optimization passes. 1669 // Delete basic blocks, which optimization passes may have killed. 1670 MPM.addPass(createModuleToFunctionPassAdaptor( 1671 SimplifyCFGPass(SimplifyCFGOptions().hoistCommonInsts(true)))); 1672 1673 // Drop bodies of available eternally objects to improve GlobalDCE. 1674 MPM.addPass(EliminateAvailableExternallyPass()); 1675 1676 // Now that we have optimized the program, discard unreachable functions. 1677 MPM.addPass(GlobalDCEPass()); 1678 1679 if (PTO.MergeFunctions) 1680 MPM.addPass(MergeFunctionsPass()); 1681 1682 // Emit annotation remarks. 1683 addAnnotationRemarksPass(MPM); 1684 1685 return MPM; 1686 } 1687 1688 ModulePassManager PassBuilder::buildO0DefaultPipeline(OptimizationLevel Level, 1689 bool LTOPreLink) { 1690 assert(Level == OptimizationLevel::O0 && 1691 "buildO0DefaultPipeline should only be used with O0"); 1692 1693 ModulePassManager MPM; 1694 1695 // Perform pseudo probe instrumentation in O0 mode. This is for the 1696 // consistency between different build modes. For example, a LTO build can be 1697 // mixed with an O0 prelink and an O2 postlink. Loading a sample profile in 1698 // the postlink will require pseudo probe instrumentation in the prelink. 1699 if (PGOOpt && PGOOpt->PseudoProbeForProfiling) 1700 MPM.addPass(SampleProfileProbePass(TM)); 1701 1702 if (PGOOpt && (PGOOpt->Action == PGOOptions::IRInstr || 1703 PGOOpt->Action == PGOOptions::IRUse)) 1704 addPGOInstrPassesForO0( 1705 MPM, 1706 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), 1707 /* IsCS */ false, PGOOpt->ProfileFile, PGOOpt->ProfileRemappingFile); 1708 1709 for (auto &C : PipelineStartEPCallbacks) 1710 C(MPM, Level); 1711 1712 if (PGOOpt && PGOOpt->DebugInfoForProfiling) 1713 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1714 1715 for (auto &C : PipelineEarlySimplificationEPCallbacks) 1716 C(MPM, Level); 1717 1718 // Build a minimal pipeline based on the semantics required by LLVM, 1719 // which is just that always inlining occurs. Further, disable generating 1720 // lifetime intrinsics to avoid enabling further optimizations during 1721 // code generation. 1722 MPM.addPass(AlwaysInlinerPass( 1723 /*InsertLifetimeIntrinsics=*/false)); 1724 1725 if (PTO.MergeFunctions) 1726 MPM.addPass(MergeFunctionsPass()); 1727 1728 if (EnableMatrix) 1729 MPM.addPass( 1730 createModuleToFunctionPassAdaptor(LowerMatrixIntrinsicsPass(true))); 1731 1732 if (!CGSCCOptimizerLateEPCallbacks.empty()) { 1733 CGSCCPassManager CGPM; 1734 for (auto &C : CGSCCOptimizerLateEPCallbacks) 1735 C(CGPM, Level); 1736 if (!CGPM.isEmpty()) 1737 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1738 } 1739 if (!LateLoopOptimizationsEPCallbacks.empty()) { 1740 LoopPassManager LPM; 1741 for (auto &C : LateLoopOptimizationsEPCallbacks) 1742 C(LPM, Level); 1743 if (!LPM.isEmpty()) { 1744 MPM.addPass(createModuleToFunctionPassAdaptor( 1745 createFunctionToLoopPassAdaptor(std::move(LPM)))); 1746 } 1747 } 1748 if (!LoopOptimizerEndEPCallbacks.empty()) { 1749 LoopPassManager LPM; 1750 for (auto &C : LoopOptimizerEndEPCallbacks) 1751 C(LPM, Level); 1752 if (!LPM.isEmpty()) { 1753 MPM.addPass(createModuleToFunctionPassAdaptor( 1754 createFunctionToLoopPassAdaptor(std::move(LPM)))); 1755 } 1756 } 1757 if (!ScalarOptimizerLateEPCallbacks.empty()) { 1758 FunctionPassManager FPM; 1759 for (auto &C : ScalarOptimizerLateEPCallbacks) 1760 C(FPM, Level); 1761 if (!FPM.isEmpty()) 1762 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1763 } 1764 if (!VectorizerStartEPCallbacks.empty()) { 1765 FunctionPassManager FPM; 1766 for (auto &C : VectorizerStartEPCallbacks) 1767 C(FPM, Level); 1768 if (!FPM.isEmpty()) 1769 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1770 } 1771 1772 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); 1773 CGSCCPassManager CGPM; 1774 CGPM.addPass(CoroSplitPass()); 1775 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1776 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1777 1778 for (auto &C : OptimizerLastEPCallbacks) 1779 C(MPM, Level); 1780 1781 if (LTOPreLink) 1782 addRequiredLTOPreLinkPasses(MPM); 1783 1784 MPM.addPass(createModuleToFunctionPassAdaptor(AnnotationRemarksPass())); 1785 1786 return MPM; 1787 } 1788 1789 AAManager PassBuilder::buildDefaultAAPipeline() { 1790 AAManager AA; 1791 1792 // The order in which these are registered determines their priority when 1793 // being queried. 1794 1795 // First we register the basic alias analysis that provides the majority of 1796 // per-function local AA logic. This is a stateless, on-demand local set of 1797 // AA techniques. 1798 AA.registerFunctionAnalysis<BasicAA>(); 1799 1800 // Next we query fast, specialized alias analyses that wrap IR-embedded 1801 // information about aliasing. 1802 AA.registerFunctionAnalysis<ScopedNoAliasAA>(); 1803 AA.registerFunctionAnalysis<TypeBasedAA>(); 1804 1805 // Add support for querying global aliasing information when available. 1806 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module 1807 // analysis, all that the `AAManager` can do is query for any *cached* 1808 // results from `GlobalsAA` through a readonly proxy. 1809 AA.registerModuleAnalysis<GlobalsAA>(); 1810 1811 // Add target-specific alias analyses. 1812 if (TM) 1813 TM->registerDefaultAliasAnalyses(AA); 1814 1815 return AA; 1816 } 1817