1 //===- Parsing, selection, and 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/Passes/PassBuilder.h" 18 #include "llvm/ADT/StringSwitch.h" 19 #include "llvm/Analysis/AliasAnalysis.h" 20 #include "llvm/Analysis/AliasAnalysisEvaluator.h" 21 #include "llvm/Analysis/AssumptionCache.h" 22 #include "llvm/Analysis/BasicAliasAnalysis.h" 23 #include "llvm/Analysis/BlockFrequencyInfo.h" 24 #include "llvm/Analysis/BranchProbabilityInfo.h" 25 #include "llvm/Analysis/CFGPrinter.h" 26 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 27 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 28 #include "llvm/Analysis/CGSCCPassManager.h" 29 #include "llvm/Analysis/CallGraph.h" 30 #include "llvm/Analysis/DDG.h" 31 #include "llvm/Analysis/DemandedBits.h" 32 #include "llvm/Analysis/DependenceAnalysis.h" 33 #include "llvm/Analysis/DominanceFrontier.h" 34 #include "llvm/Analysis/GlobalsModRef.h" 35 #include "llvm/Analysis/IVUsers.h" 36 #include "llvm/Analysis/LazyCallGraph.h" 37 #include "llvm/Analysis/LazyValueInfo.h" 38 #include "llvm/Analysis/LoopAccessAnalysis.h" 39 #include "llvm/Analysis/LoopCacheAnalysis.h" 40 #include "llvm/Analysis/LoopInfo.h" 41 #include "llvm/Analysis/LoopNestAnalysis.h" 42 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 43 #include "llvm/Analysis/MemorySSA.h" 44 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 45 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 46 #include "llvm/Analysis/PhiValues.h" 47 #include "llvm/Analysis/PostDominators.h" 48 #include "llvm/Analysis/ProfileSummaryInfo.h" 49 #include "llvm/Analysis/RegionInfo.h" 50 #include "llvm/Analysis/ScalarEvolution.h" 51 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 52 #include "llvm/Analysis/ScopedNoAliasAA.h" 53 #include "llvm/Analysis/StackSafetyAnalysis.h" 54 #include "llvm/Analysis/TargetLibraryInfo.h" 55 #include "llvm/Analysis/TargetTransformInfo.h" 56 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 57 #include "llvm/CodeGen/MachineModuleInfo.h" 58 #include "llvm/CodeGen/PreISelIntrinsicLowering.h" 59 #include "llvm/CodeGen/UnreachableBlockElim.h" 60 #include "llvm/IR/Dominators.h" 61 #include "llvm/IR/IRPrintingPasses.h" 62 #include "llvm/IR/PassManager.h" 63 #include "llvm/IR/SafepointIRVerifier.h" 64 #include "llvm/IR/Verifier.h" 65 #include "llvm/Support/CommandLine.h" 66 #include "llvm/Support/Debug.h" 67 #include "llvm/Support/FormatVariadic.h" 68 #include "llvm/Support/Regex.h" 69 #include "llvm/Target/TargetMachine.h" 70 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 71 #include "llvm/Transforms/Coroutines/CoroCleanup.h" 72 #include "llvm/Transforms/Coroutines/CoroEarly.h" 73 #include "llvm/Transforms/Coroutines/CoroElide.h" 74 #include "llvm/Transforms/Coroutines/CoroSplit.h" 75 #include "llvm/Transforms/IPO/AlwaysInliner.h" 76 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 77 #include "llvm/Transforms/IPO/Attributor.h" 78 #include "llvm/Transforms/IPO/CalledValuePropagation.h" 79 #include "llvm/Transforms/IPO/ConstantMerge.h" 80 #include "llvm/Transforms/IPO/CrossDSOCFI.h" 81 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 82 #include "llvm/Transforms/IPO/ElimAvailExtern.h" 83 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 84 #include "llvm/Transforms/IPO/FunctionAttrs.h" 85 #include "llvm/Transforms/IPO/FunctionImport.h" 86 #include "llvm/Transforms/IPO/GlobalDCE.h" 87 #include "llvm/Transforms/IPO/GlobalOpt.h" 88 #include "llvm/Transforms/IPO/GlobalSplit.h" 89 #include "llvm/Transforms/IPO/HotColdSplitting.h" 90 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 91 #include "llvm/Transforms/IPO/Inliner.h" 92 #include "llvm/Transforms/IPO/Internalize.h" 93 #include "llvm/Transforms/IPO/LowerTypeTests.h" 94 #include "llvm/Transforms/IPO/MergeFunctions.h" 95 #include "llvm/Transforms/IPO/OpenMPOpt.h" 96 #include "llvm/Transforms/IPO/PartialInlining.h" 97 #include "llvm/Transforms/IPO/SCCP.h" 98 #include "llvm/Transforms/IPO/SampleProfile.h" 99 #include "llvm/Transforms/IPO/StripDeadPrototypes.h" 100 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h" 101 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 102 #include "llvm/Transforms/InstCombine/InstCombine.h" 103 #include "llvm/Transforms/Instrumentation.h" 104 #include "llvm/Transforms/Instrumentation/AddressSanitizer.h" 105 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 106 #include "llvm/Transforms/Instrumentation/CGProfile.h" 107 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" 108 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 109 #include "llvm/Transforms/Instrumentation/HWAddressSanitizer.h" 110 #include "llvm/Transforms/Instrumentation/InstrOrderFile.h" 111 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 112 #include "llvm/Transforms/Instrumentation/MemorySanitizer.h" 113 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 114 #include "llvm/Transforms/Instrumentation/PoisonChecking.h" 115 #include "llvm/Transforms/Instrumentation/SanitizerCoverage.h" 116 #include "llvm/Transforms/Instrumentation/ThreadSanitizer.h" 117 #include "llvm/Transforms/Scalar/ADCE.h" 118 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 119 #include "llvm/Transforms/Scalar/BDCE.h" 120 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 121 #include "llvm/Transforms/Scalar/ConstantHoisting.h" 122 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 123 #include "llvm/Transforms/Scalar/DCE.h" 124 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 125 #include "llvm/Transforms/Scalar/DivRemPairs.h" 126 #include "llvm/Transforms/Scalar/EarlyCSE.h" 127 #include "llvm/Transforms/Scalar/Float2Int.h" 128 #include "llvm/Transforms/Scalar/GVN.h" 129 #include "llvm/Transforms/Scalar/GuardWidening.h" 130 #include "llvm/Transforms/Scalar/IVUsersPrinter.h" 131 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 132 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h" 133 #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 134 #include "llvm/Transforms/Scalar/JumpThreading.h" 135 #include "llvm/Transforms/Scalar/LICM.h" 136 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h" 137 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h" 138 #include "llvm/Transforms/Scalar/LoopDeletion.h" 139 #include "llvm/Transforms/Scalar/LoopDistribute.h" 140 #include "llvm/Transforms/Scalar/LoopFuse.h" 141 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 142 #include "llvm/Transforms/Scalar/LoopInstSimplify.h" 143 #include "llvm/Transforms/Scalar/LoopLoadElimination.h" 144 #include "llvm/Transforms/Scalar/LoopPassManager.h" 145 #include "llvm/Transforms/Scalar/LoopPredication.h" 146 #include "llvm/Transforms/Scalar/LoopRotation.h" 147 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 148 #include "llvm/Transforms/Scalar/LoopSink.h" 149 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 150 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h" 151 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 152 #include "llvm/Transforms/Scalar/LowerAtomic.h" 153 #include "llvm/Transforms/Scalar/LowerConstantIntrinsics.h" 154 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 155 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h" 156 #include "llvm/Transforms/Scalar/LowerMatrixIntrinsics.h" 157 #include "llvm/Transforms/Scalar/LowerWidenableCondition.h" 158 #include "llvm/Transforms/Scalar/MakeGuardsExplicit.h" 159 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 160 #include "llvm/Transforms/Scalar/MergeICmps.h" 161 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 162 #include "llvm/Transforms/Scalar/NaryReassociate.h" 163 #include "llvm/Transforms/Scalar/NewGVN.h" 164 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h" 165 #include "llvm/Transforms/Scalar/Reassociate.h" 166 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h" 167 #include "llvm/Transforms/Scalar/SCCP.h" 168 #include "llvm/Transforms/Scalar/SROA.h" 169 #include "llvm/Transforms/Scalar/Scalarizer.h" 170 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 171 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 172 #include "llvm/Transforms/Scalar/Sink.h" 173 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h" 174 #include "llvm/Transforms/Scalar/SpeculativeExecution.h" 175 #include "llvm/Transforms/Scalar/TailRecursionElimination.h" 176 #include "llvm/Transforms/Scalar/WarnMissedTransforms.h" 177 #include "llvm/Transforms/Utils/AddDiscriminators.h" 178 #include "llvm/Transforms/Utils/AssumeBundleBuilder.h" 179 #include "llvm/Transforms/Utils/BreakCriticalEdges.h" 180 #include "llvm/Transforms/Utils/CanonicalizeAliases.h" 181 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" 182 #include "llvm/Transforms/Utils/InjectTLIMappings.h" 183 #include "llvm/Transforms/Utils/LCSSA.h" 184 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" 185 #include "llvm/Transforms/Utils/LoopSimplify.h" 186 #include "llvm/Transforms/Utils/LowerInvoke.h" 187 #include "llvm/Transforms/Utils/Mem2Reg.h" 188 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 189 #include "llvm/Transforms/Utils/SymbolRewriter.h" 190 #include "llvm/Transforms/Vectorize/LoadStoreVectorizer.h" 191 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 192 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 193 #include "llvm/Transforms/Vectorize/VectorCombine.h" 194 195 using namespace llvm; 196 197 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations", 198 cl::ReallyHidden, cl::init(4)); 199 static cl::opt<bool> 200 RunPartialInlining("enable-npm-partial-inlining", cl::init(false), 201 cl::Hidden, cl::ZeroOrMore, 202 cl::desc("Run Partial inlinining pass")); 203 204 static cl::opt<int> PreInlineThreshold( 205 "npm-preinline-threshold", cl::Hidden, cl::init(75), cl::ZeroOrMore, 206 cl::desc("Control the amount of inlining in pre-instrumentation inliner " 207 "(default = 75)")); 208 209 static cl::opt<bool> 210 RunNewGVN("enable-npm-newgvn", cl::init(false), 211 cl::Hidden, cl::ZeroOrMore, 212 cl::desc("Run NewGVN instead of GVN")); 213 214 static cl::opt<bool> EnableGVNHoist( 215 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden, 216 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)")); 217 218 static cl::opt<bool> EnableGVNSink( 219 "enable-npm-gvn-sink", cl::init(false), cl::Hidden, 220 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)")); 221 222 static cl::opt<bool> EnableUnrollAndJam( 223 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden, 224 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)")); 225 226 static cl::opt<bool> EnableSyntheticCounts( 227 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, 228 cl::desc("Run synthetic function entry count generation " 229 "pass")); 230 231 static const Regex DefaultAliasRegex( 232 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$"); 233 234 // This option is used in simplifying testing SampleFDO optimizations for 235 // profile loading. 236 static cl::opt<bool> 237 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden, 238 cl::desc("Enable control height reduction optimization (CHR)")); 239 240 static cl::opt<bool> EnableCallGraphProfile( 241 "enable-npm-call-graph-profile", cl::init(true), cl::Hidden, 242 cl::desc("Enable call graph profile pass for the new PM (default = on)")); 243 244 PipelineTuningOptions::PipelineTuningOptions() { 245 LoopInterleaving = true; 246 LoopVectorization = true; 247 SLPVectorization = false; 248 LoopUnrolling = true; 249 ForgetAllSCEVInLoopUnroll = ForgetSCEVInLoopUnroll; 250 Coroutines = false; 251 LicmMssaOptCap = SetLicmMssaOptCap; 252 LicmMssaNoAccForPromotionCap = SetLicmMssaNoAccForPromotionCap; 253 CallGraphProfile = EnableCallGraphProfile; 254 } 255 256 extern cl::opt<bool> EnableHotColdSplit; 257 extern cl::opt<bool> EnableOrderFileInstrumentation; 258 259 extern cl::opt<bool> FlattenedProfileUsed; 260 261 extern cl::opt<bool> DisableAttributor; 262 263 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O0 = { 264 /*SpeedLevel*/ 0, 265 /*SizeLevel*/ 0}; 266 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O1 = { 267 /*SpeedLevel*/ 1, 268 /*SizeLevel*/ 0}; 269 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O2 = { 270 /*SpeedLevel*/ 2, 271 /*SizeLevel*/ 0}; 272 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::O3 = { 273 /*SpeedLevel*/ 3, 274 /*SizeLevel*/ 0}; 275 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::Os = { 276 /*SpeedLevel*/ 2, 277 /*SizeLevel*/ 1}; 278 const PassBuilder::OptimizationLevel PassBuilder::OptimizationLevel::Oz = { 279 /*SpeedLevel*/ 2, 280 /*SizeLevel*/ 2}; 281 282 namespace { 283 284 /// No-op module pass which does nothing. 285 struct NoOpModulePass { 286 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) { 287 return PreservedAnalyses::all(); 288 } 289 static StringRef name() { return "NoOpModulePass"; } 290 }; 291 292 /// No-op module analysis. 293 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> { 294 friend AnalysisInfoMixin<NoOpModuleAnalysis>; 295 static AnalysisKey Key; 296 297 public: 298 struct Result {}; 299 Result run(Module &, ModuleAnalysisManager &) { return Result(); } 300 static StringRef name() { return "NoOpModuleAnalysis"; } 301 }; 302 303 /// No-op CGSCC pass which does nothing. 304 struct NoOpCGSCCPass { 305 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &, 306 LazyCallGraph &, CGSCCUpdateResult &UR) { 307 return PreservedAnalyses::all(); 308 } 309 static StringRef name() { return "NoOpCGSCCPass"; } 310 }; 311 312 /// No-op CGSCC analysis. 313 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> { 314 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>; 315 static AnalysisKey Key; 316 317 public: 318 struct Result {}; 319 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) { 320 return Result(); 321 } 322 static StringRef name() { return "NoOpCGSCCAnalysis"; } 323 }; 324 325 /// No-op function pass which does nothing. 326 struct NoOpFunctionPass { 327 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) { 328 return PreservedAnalyses::all(); 329 } 330 static StringRef name() { return "NoOpFunctionPass"; } 331 }; 332 333 /// No-op function analysis. 334 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> { 335 friend AnalysisInfoMixin<NoOpFunctionAnalysis>; 336 static AnalysisKey Key; 337 338 public: 339 struct Result {}; 340 Result run(Function &, FunctionAnalysisManager &) { return Result(); } 341 static StringRef name() { return "NoOpFunctionAnalysis"; } 342 }; 343 344 /// No-op loop pass which does nothing. 345 struct NoOpLoopPass { 346 PreservedAnalyses run(Loop &L, LoopAnalysisManager &, 347 LoopStandardAnalysisResults &, LPMUpdater &) { 348 return PreservedAnalyses::all(); 349 } 350 static StringRef name() { return "NoOpLoopPass"; } 351 }; 352 353 /// No-op loop analysis. 354 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> { 355 friend AnalysisInfoMixin<NoOpLoopAnalysis>; 356 static AnalysisKey Key; 357 358 public: 359 struct Result {}; 360 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) { 361 return Result(); 362 } 363 static StringRef name() { return "NoOpLoopAnalysis"; } 364 }; 365 366 AnalysisKey NoOpModuleAnalysis::Key; 367 AnalysisKey NoOpCGSCCAnalysis::Key; 368 AnalysisKey NoOpFunctionAnalysis::Key; 369 AnalysisKey NoOpLoopAnalysis::Key; 370 371 } // End anonymous namespace. 372 373 void PassBuilder::invokePeepholeEPCallbacks( 374 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 375 for (auto &C : PeepholeEPCallbacks) 376 C(FPM, Level); 377 } 378 379 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) { 380 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 381 MAM.registerPass([&] { return CREATE_PASS; }); 382 #include "PassRegistry.def" 383 384 for (auto &C : ModuleAnalysisRegistrationCallbacks) 385 C(MAM); 386 } 387 388 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) { 389 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 390 CGAM.registerPass([&] { return CREATE_PASS; }); 391 #include "PassRegistry.def" 392 393 for (auto &C : CGSCCAnalysisRegistrationCallbacks) 394 C(CGAM); 395 } 396 397 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) { 398 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 399 FAM.registerPass([&] { return CREATE_PASS; }); 400 #include "PassRegistry.def" 401 402 for (auto &C : FunctionAnalysisRegistrationCallbacks) 403 C(FAM); 404 } 405 406 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) { 407 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 408 LAM.registerPass([&] { return CREATE_PASS; }); 409 #include "PassRegistry.def" 410 411 for (auto &C : LoopAnalysisRegistrationCallbacks) 412 C(LAM); 413 } 414 415 FunctionPassManager 416 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, 417 ThinLTOPhase Phase, 418 bool DebugLogging) { 419 assert(Level != OptimizationLevel::O0 && "Must request optimizations!"); 420 FunctionPassManager FPM(DebugLogging); 421 422 // Form SSA out of local memory accesses after breaking apart aggregates into 423 // scalars. 424 FPM.addPass(SROA()); 425 426 // Catch trivial redundancies 427 FPM.addPass(EarlyCSEPass(true /* Enable mem-ssa. */)); 428 429 // Hoisting of scalars and load expressions. 430 if (Level.getSpeedupLevel() > 1) { 431 if (EnableGVNHoist) 432 FPM.addPass(GVNHoistPass()); 433 434 // Global value numbering based sinking. 435 if (EnableGVNSink) { 436 FPM.addPass(GVNSinkPass()); 437 FPM.addPass(SimplifyCFGPass()); 438 } 439 } 440 441 // Speculative execution if the target has divergent branches; otherwise nop. 442 if (Level.getSpeedupLevel() > 1) { 443 FPM.addPass(SpeculativeExecutionPass()); 444 445 // Optimize based on known information about branches, and cleanup afterward. 446 FPM.addPass(JumpThreadingPass()); 447 FPM.addPass(CorrelatedValuePropagationPass()); 448 } 449 FPM.addPass(SimplifyCFGPass()); 450 if (Level == OptimizationLevel::O3) 451 FPM.addPass(AggressiveInstCombinePass()); 452 FPM.addPass(InstCombinePass()); 453 454 if (!Level.isOptimizingForSize()) 455 FPM.addPass(LibCallsShrinkWrapPass()); 456 457 invokePeepholeEPCallbacks(FPM, Level); 458 459 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy 460 // using the size value profile. Don't perform this when optimizing for size. 461 if (PGOOpt && PGOOpt->Action == PGOOptions::IRUse && 462 (Level.getSpeedupLevel() > 1 && !Level.isOptimizingForSize())) 463 FPM.addPass(PGOMemOPSizeOpt()); 464 465 // TODO: Investigate the cost/benefit of tail call elimination on debugging. 466 if (Level.getSpeedupLevel() > 1) 467 FPM.addPass(TailCallElimPass()); 468 FPM.addPass(SimplifyCFGPass()); 469 470 // Form canonically associated expression trees, and simplify the trees using 471 // basic mathematical properties. For example, this will form (nearly) 472 // minimal multiplication trees. 473 FPM.addPass(ReassociatePass()); 474 475 // Add the primary loop simplification pipeline. 476 // FIXME: Currently this is split into two loop pass pipelines because we run 477 // some function passes in between them. These can and should be removed 478 // and/or replaced by scheduling the loop pass equivalents in the correct 479 // positions. But those equivalent passes aren't powerful enough yet. 480 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 481 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 482 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 483 // `LoopInstSimplify`. 484 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging); 485 486 // Simplify the loop body. We do this initially to clean up after other loop 487 // passes run, either when iterating on a loop or on inner loops with 488 // implications on the outer loop. 489 LPM1.addPass(LoopInstSimplifyPass()); 490 LPM1.addPass(LoopSimplifyCFGPass()); 491 492 // Rotate Loop - disable header duplication at -Oz 493 LPM1.addPass(LoopRotatePass(Level != OptimizationLevel::Oz)); 494 // TODO: Investigate promotion cap for O1. 495 LPM1.addPass(LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap)); 496 LPM1.addPass(SimpleLoopUnswitchPass()); 497 LPM2.addPass(IndVarSimplifyPass()); 498 LPM2.addPass(LoopIdiomRecognizePass()); 499 500 for (auto &C : LateLoopOptimizationsEPCallbacks) 501 C(LPM2, Level); 502 503 LPM2.addPass(LoopDeletionPass()); 504 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 505 // because it changes IR to makes profile annotation in back compile 506 // inaccurate. 507 if ((Phase != ThinLTOPhase::PreLink || !PGOOpt || 508 PGOOpt->Action != PGOOptions::SampleUse) && 509 PTO.LoopUnrolling) 510 LPM2.addPass(LoopFullUnrollPass(Level.getSpeedupLevel(), 511 /*OnlyWhenForced=*/false, 512 PTO.ForgetAllSCEVInLoopUnroll)); 513 514 for (auto &C : LoopOptimizerEndEPCallbacks) 515 C(LPM2, Level); 516 517 // We provide the opt remark emitter pass for LICM to use. We only need to do 518 // this once as it is immutable. 519 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 520 FPM.addPass(createFunctionToLoopPassAdaptor( 521 std::move(LPM1), EnableMSSALoopDependency, DebugLogging)); 522 FPM.addPass(SimplifyCFGPass()); 523 FPM.addPass(InstCombinePass()); 524 // The loop passes in LPM2 (IndVarSimplifyPass, LoopIdiomRecognizePass, 525 // LoopDeletionPass and LoopFullUnrollPass) do not preserve MemorySSA. 526 // *All* loop passes must preserve it, in order to be able to use it. 527 FPM.addPass(createFunctionToLoopPassAdaptor( 528 std::move(LPM2), /*UseMemorySSA=*/false, DebugLogging)); 529 530 // Delete small array after loop unroll. 531 FPM.addPass(SROA()); 532 533 // Eliminate redundancies. 534 if (Level != OptimizationLevel::O1) { 535 // These passes add substantial compile time so skip them at O1. 536 FPM.addPass(MergedLoadStoreMotionPass()); 537 if (RunNewGVN) 538 FPM.addPass(NewGVNPass()); 539 else 540 FPM.addPass(GVN()); 541 } 542 543 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 544 FPM.addPass(MemCpyOptPass()); 545 546 // Sparse conditional constant propagation. 547 // FIXME: It isn't clear why we do this *after* loop passes rather than 548 // before... 549 FPM.addPass(SCCPPass()); 550 551 // Delete dead bit computations (instcombine runs after to fold away the dead 552 // computations, and then ADCE will run later to exploit any new DCE 553 // opportunities that creates). 554 FPM.addPass(BDCEPass()); 555 556 // Run instcombine after redundancy and dead bit elimination to exploit 557 // opportunities opened up by them. 558 FPM.addPass(InstCombinePass()); 559 invokePeepholeEPCallbacks(FPM, Level); 560 561 // Re-consider control flow based optimizations after redundancy elimination, 562 // redo DCE, etc. 563 if (Level.getSpeedupLevel() > 1) { 564 FPM.addPass(JumpThreadingPass()); 565 FPM.addPass(CorrelatedValuePropagationPass()); 566 FPM.addPass(DSEPass()); 567 FPM.addPass(createFunctionToLoopPassAdaptor( 568 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 569 EnableMSSALoopDependency, DebugLogging)); 570 } 571 572 if (PTO.Coroutines) 573 FPM.addPass(CoroElidePass()); 574 575 for (auto &C : ScalarOptimizerLateEPCallbacks) 576 C(FPM, Level); 577 578 // Finally, do an expensive DCE pass to catch all the dead code exposed by 579 // the simplifications and basic cleanup after all the simplifications. 580 // TODO: Investigate if this is too expensive. 581 FPM.addPass(ADCEPass()); 582 FPM.addPass(SimplifyCFGPass()); 583 FPM.addPass(InstCombinePass()); 584 invokePeepholeEPCallbacks(FPM, Level); 585 586 if (EnableCHR && Level == OptimizationLevel::O3 && PGOOpt && 587 (PGOOpt->Action == PGOOptions::IRUse || 588 PGOOpt->Action == PGOOptions::SampleUse)) 589 FPM.addPass(ControlHeightReductionPass()); 590 591 return FPM; 592 } 593 594 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging, 595 PassBuilder::OptimizationLevel Level, 596 bool RunProfileGen, bool IsCS, 597 std::string ProfileFile, 598 std::string ProfileRemappingFile) { 599 assert(Level != OptimizationLevel::O0 && "Not expecting O0 here!"); 600 // Generally running simplification passes and the inliner with an high 601 // threshold results in smaller executables, but there may be cases where 602 // the size grows, so let's be conservative here and skip this simplification 603 // at -Os/Oz. We will not do this inline for context sensistive PGO (when 604 // IsCS is true). 605 if (!Level.isOptimizingForSize() && !IsCS) { 606 InlineParams IP; 607 608 IP.DefaultThreshold = PreInlineThreshold; 609 610 // FIXME: The hint threshold has the same value used by the regular inliner. 611 // This should probably be lowered after performance testing. 612 // FIXME: this comment is cargo culted from the old pass manager, revisit). 613 IP.HintThreshold = 325; 614 615 CGSCCPassManager CGPipeline(DebugLogging); 616 617 CGPipeline.addPass(InlinerPass(IP)); 618 619 FunctionPassManager FPM; 620 FPM.addPass(SROA()); 621 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies. 622 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks. 623 FPM.addPass(InstCombinePass()); // Combine silly sequences. 624 invokePeepholeEPCallbacks(FPM, Level); 625 626 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 627 628 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline))); 629 630 // Delete anything that is now dead to make sure that we don't instrument 631 // dead code. Instrumentation can end up keeping dead code around and 632 // dramatically increase code size. 633 MPM.addPass(GlobalDCEPass()); 634 } 635 636 if (!RunProfileGen) { 637 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 638 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 639 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 640 // RequireAnalysisPass for PSI before subsequent non-module passes. 641 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 642 return; 643 } 644 645 // Perform PGO instrumentation. 646 MPM.addPass(PGOInstrumentationGen(IsCS)); 647 648 FunctionPassManager FPM; 649 FPM.addPass(createFunctionToLoopPassAdaptor( 650 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging)); 651 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 652 653 // Add the profile lowering pass. 654 InstrProfOptions Options; 655 if (!ProfileFile.empty()) 656 Options.InstrProfileOutput = ProfileFile; 657 // Do counter promotion at Level greater than O0. 658 Options.DoCounterPromotion = true; 659 Options.UseBFIInPromotion = IsCS; 660 MPM.addPass(InstrProfiling(Options, IsCS)); 661 } 662 663 void PassBuilder::addPGOInstrPassesForO0(ModulePassManager &MPM, 664 bool DebugLogging, bool RunProfileGen, 665 bool IsCS, std::string ProfileFile, 666 std::string ProfileRemappingFile) { 667 if (!RunProfileGen) { 668 assert(!ProfileFile.empty() && "Profile use expecting a profile file!"); 669 MPM.addPass(PGOInstrumentationUse(ProfileFile, ProfileRemappingFile, IsCS)); 670 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 671 // RequireAnalysisPass for PSI before subsequent non-module passes. 672 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 673 return; 674 } 675 676 // Perform PGO instrumentation. 677 MPM.addPass(PGOInstrumentationGen(IsCS)); 678 // Add the profile lowering pass. 679 InstrProfOptions Options; 680 if (!ProfileFile.empty()) 681 Options.InstrProfileOutput = ProfileFile; 682 // Do not do counter promotion at O0. 683 Options.DoCounterPromotion = false; 684 Options.UseBFIInPromotion = IsCS; 685 MPM.addPass(InstrProfiling(Options, IsCS)); 686 } 687 688 static InlineParams 689 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) { 690 return getInlineParams(Level.getSpeedupLevel(), Level.getSizeLevel()); 691 } 692 693 ModulePassManager 694 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, 695 ThinLTOPhase Phase, 696 bool DebugLogging) { 697 ModulePassManager MPM(DebugLogging); 698 699 bool HasSampleProfile = PGOOpt && (PGOOpt->Action == PGOOptions::SampleUse); 700 701 // In ThinLTO mode, when flattened profile is used, all the available 702 // profile information will be annotated in PreLink phase so there is 703 // no need to load the profile again in PostLink. 704 bool LoadSampleProfile = 705 HasSampleProfile && 706 !(FlattenedProfileUsed && Phase == ThinLTOPhase::PostLink); 707 708 // During the ThinLTO backend phase we perform early indirect call promotion 709 // here, before globalopt. Otherwise imported available_externally functions 710 // look unreferenced and are removed. If we are going to load the sample 711 // profile then defer until later. 712 // TODO: See if we can move later and consolidate with the location where 713 // we perform ICP when we are loading a sample profile. 714 // TODO: We pass HasSampleProfile (whether there was a sample profile file 715 // passed to the compile) to the SamplePGO flag of ICP. This is used to 716 // determine whether the new direct calls are annotated with prof metadata. 717 // Ideally this should be determined from whether the IR is annotated with 718 // sample profile, and not whether the a sample profile was provided on the 719 // command line. E.g. for flattened profiles where we will not be reloading 720 // the sample profile in the ThinLTO backend, we ideally shouldn't have to 721 // provide the sample profile file. 722 if (Phase == ThinLTOPhase::PostLink && !LoadSampleProfile) 723 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, HasSampleProfile)); 724 725 // Do basic inference of function attributes from known properties of system 726 // libraries and other oracles. 727 MPM.addPass(InferFunctionAttrsPass()); 728 729 // Create an early function pass manager to cleanup the output of the 730 // frontend. 731 FunctionPassManager EarlyFPM(DebugLogging); 732 EarlyFPM.addPass(SimplifyCFGPass()); 733 EarlyFPM.addPass(SROA()); 734 EarlyFPM.addPass(EarlyCSEPass()); 735 EarlyFPM.addPass(LowerExpectIntrinsicPass()); 736 if (PTO.Coroutines) 737 EarlyFPM.addPass(CoroEarlyPass()); 738 if (Level == OptimizationLevel::O3) 739 EarlyFPM.addPass(CallSiteSplittingPass()); 740 741 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation 742 // to convert bitcast to direct calls so that they can be inlined during the 743 // profile annotation prepration step. 744 // More details about SamplePGO design can be found in: 745 // https://research.google.com/pubs/pub45290.html 746 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured. 747 if (LoadSampleProfile) 748 EarlyFPM.addPass(InstCombinePass()); 749 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 750 751 if (LoadSampleProfile) { 752 // Annotate sample profile right after early FPM to ensure freshness of 753 // the debug info. 754 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 755 PGOOpt->ProfileRemappingFile, 756 Phase == ThinLTOPhase::PreLink)); 757 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 758 // RequireAnalysisPass for PSI before subsequent non-module passes. 759 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 760 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard 761 // for the profile annotation to be accurate in the ThinLTO backend. 762 if (Phase != ThinLTOPhase::PreLink) 763 // We perform early indirect call promotion here, before globalopt. 764 // This is important for the ThinLTO backend phase because otherwise 765 // imported available_externally functions look unreferenced and are 766 // removed. 767 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink, 768 true /* SamplePGO */)); 769 } 770 771 if (!DisableAttributor) 772 MPM.addPass(AttributorPass()); 773 774 // Interprocedural constant propagation now that basic cleanup has occurred 775 // and prior to optimizing globals. 776 // FIXME: This position in the pipeline hasn't been carefully considered in 777 // years, it should be re-analyzed. 778 MPM.addPass(IPSCCPPass()); 779 780 // Attach metadata to indirect call sites indicating the set of functions 781 // they may target at run-time. This should follow IPSCCP. 782 MPM.addPass(CalledValuePropagationPass()); 783 784 // Optimize globals to try and fold them into constants. 785 MPM.addPass(GlobalOptPass()); 786 787 // Promote any localized globals to SSA registers. 788 // FIXME: Should this instead by a run of SROA? 789 // FIXME: We should probably run instcombine and simplify-cfg afterward to 790 // delete control flows that are dead once globals have been folded to 791 // constants. 792 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 793 794 // Remove any dead arguments exposed by cleanups and constand folding 795 // globals. 796 MPM.addPass(DeadArgumentEliminationPass()); 797 798 // Create a small function pass pipeline to cleanup after all the global 799 // optimizations. 800 FunctionPassManager GlobalCleanupPM(DebugLogging); 801 GlobalCleanupPM.addPass(InstCombinePass()); 802 invokePeepholeEPCallbacks(GlobalCleanupPM, Level); 803 804 GlobalCleanupPM.addPass(SimplifyCFGPass()); 805 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM))); 806 807 // Add all the requested passes for instrumentation PGO, if requested. 808 if (PGOOpt && Phase != ThinLTOPhase::PostLink && 809 (PGOOpt->Action == PGOOptions::IRInstr || 810 PGOOpt->Action == PGOOptions::IRUse)) { 811 addPGOInstrPasses(MPM, DebugLogging, Level, 812 /* RunProfileGen */ PGOOpt->Action == PGOOptions::IRInstr, 813 /* IsCS */ false, PGOOpt->ProfileFile, 814 PGOOpt->ProfileRemappingFile); 815 MPM.addPass(PGOIndirectCallPromotion(false, false)); 816 } 817 if (PGOOpt && Phase != ThinLTOPhase::PostLink && 818 PGOOpt->CSAction == PGOOptions::CSIRInstr) 819 MPM.addPass(PGOInstrumentationGenCreateVar(PGOOpt->CSProfileGenFile)); 820 821 // Synthesize function entry counts for non-PGO compilation. 822 if (EnableSyntheticCounts && !PGOOpt) 823 MPM.addPass(SyntheticCountsPropagation()); 824 825 // Require the GlobalsAA analysis for the module so we can query it within 826 // the CGSCC pipeline. 827 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 828 829 // Require the ProfileSummaryAnalysis for the module so we can query it within 830 // the inliner pass. 831 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 832 833 // Now begin the main postorder CGSCC pipeline. 834 // FIXME: The current CGSCC pipeline has its origins in the legacy pass 835 // manager and trying to emulate its precise behavior. Much of this doesn't 836 // make a lot of sense and we should revisit the core CGSCC structure. 837 CGSCCPassManager MainCGPipeline(DebugLogging); 838 839 // Note: historically, the PruneEH pass was run first to deduce nounwind and 840 // generally clean up exception handling overhead. It isn't clear this is 841 // valuable as the inliner doesn't currently care whether it is inlining an 842 // invoke or a call. 843 844 // Run the inliner first. The theory is that we are walking bottom-up and so 845 // the callees have already been fully optimized, and we want to inline them 846 // into the callers so that our optimizations can reflect that. 847 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO 848 // because it makes profile annotation in the backend inaccurate. 849 InlineParams IP = getInlineParamsFromOptLevel(Level); 850 if (Phase == ThinLTOPhase::PreLink && PGOOpt && 851 PGOOpt->Action == PGOOptions::SampleUse) 852 IP.HotCallSiteThreshold = 0; 853 MainCGPipeline.addPass(InlinerPass(IP)); 854 855 if (!DisableAttributor) 856 MainCGPipeline.addPass(AttributorCGSCCPass()); 857 858 if (PTO.Coroutines) 859 MainCGPipeline.addPass(CoroSplitPass()); 860 861 // Now deduce any function attributes based in the current code. 862 MainCGPipeline.addPass(PostOrderFunctionAttrsPass()); 863 864 // When at O3 add argument promotion to the pass pipeline. 865 // FIXME: It isn't at all clear why this should be limited to O3. 866 if (Level == OptimizationLevel::O3) 867 MainCGPipeline.addPass(ArgumentPromotionPass()); 868 869 // Try to perform OpenMP specific optimizations. This is a (quick!) no-op if 870 // there are no OpenMP runtime calls present in the module. 871 if (Level == OptimizationLevel::O2 || Level == OptimizationLevel::O3) 872 MainCGPipeline.addPass(OpenMPOptPass()); 873 874 // Lastly, add the core function simplification pipeline nested inside the 875 // CGSCC walk. 876 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 877 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging))); 878 879 for (auto &C : CGSCCOptimizerLateEPCallbacks) 880 C(MainCGPipeline, Level); 881 882 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try 883 // to detect when we devirtualize indirect calls and iterate the SCC passes 884 // in that case to try and catch knock-on inlining or function attrs 885 // opportunities. Then we add it to the module pipeline by walking the SCCs 886 // in postorder (or bottom-up). 887 MPM.addPass( 888 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass( 889 std::move(MainCGPipeline), MaxDevirtIterations))); 890 891 return MPM; 892 } 893 894 ModulePassManager PassBuilder::buildModuleOptimizationPipeline( 895 OptimizationLevel Level, bool DebugLogging, bool LTOPreLink) { 896 ModulePassManager MPM(DebugLogging); 897 898 // Optimize globals now that the module is fully simplified. 899 MPM.addPass(GlobalOptPass()); 900 MPM.addPass(GlobalDCEPass()); 901 902 // Run partial inlining pass to partially inline functions that have 903 // large bodies. 904 if (RunPartialInlining) 905 MPM.addPass(PartialInlinerPass()); 906 907 // Remove avail extern fns and globals definitions since we aren't compiling 908 // an object file for later LTO. For LTO we want to preserve these so they 909 // are eligible for inlining at link-time. Note if they are unreferenced they 910 // will be removed by GlobalDCE later, so this only impacts referenced 911 // available externally globals. Eventually they will be suppressed during 912 // codegen, but eliminating here enables more opportunity for GlobalDCE as it 913 // may make globals referenced by available external functions dead and saves 914 // running remaining passes on the eliminated functions. These should be 915 // preserved during prelinking for link-time inlining decisions. 916 if (!LTOPreLink) 917 MPM.addPass(EliminateAvailableExternallyPass()); 918 919 if (EnableOrderFileInstrumentation) 920 MPM.addPass(InstrOrderFilePass()); 921 922 // Do RPO function attribute inference across the module to forward-propagate 923 // attributes where applicable. 924 // FIXME: Is this really an optimization rather than a canonicalization? 925 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 926 927 // Do a post inline PGO instrumentation and use pass. This is a context 928 // sensitive PGO pass. We don't want to do this in LTOPreLink phrase as 929 // cross-module inline has not been done yet. The context sensitive 930 // instrumentation is after all the inlines are done. 931 if (!LTOPreLink && PGOOpt) { 932 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 933 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true, 934 /* IsCS */ true, PGOOpt->CSProfileGenFile, 935 PGOOpt->ProfileRemappingFile); 936 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 937 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false, 938 /* IsCS */ true, PGOOpt->ProfileFile, 939 PGOOpt->ProfileRemappingFile); 940 } 941 942 // Re-require GloblasAA here prior to function passes. This is particularly 943 // useful as the above will have inlined, DCE'ed, and function-attr 944 // propagated everything. We should at this point have a reasonably minimal 945 // and richly annotated call graph. By computing aliasing and mod/ref 946 // information for all local globals here, the late loop passes and notably 947 // the vectorizer will be able to use them to help recognize vectorizable 948 // memory operations. 949 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 950 951 FunctionPassManager OptimizePM(DebugLogging); 952 OptimizePM.addPass(Float2IntPass()); 953 OptimizePM.addPass(LowerConstantIntrinsicsPass()); 954 955 // FIXME: We need to run some loop optimizations to re-rotate loops after 956 // simplify-cfg and others undo their rotation. 957 958 // Optimize the loop execution. These passes operate on entire loop nests 959 // rather than on each loop in an inside-out manner, and so they are actually 960 // function passes. 961 962 for (auto &C : VectorizerStartEPCallbacks) 963 C(OptimizePM, Level); 964 965 // First rotate loops that may have been un-rotated by prior passes. 966 OptimizePM.addPass(createFunctionToLoopPassAdaptor( 967 LoopRotatePass(), EnableMSSALoopDependency, DebugLogging)); 968 969 // Distribute loops to allow partial vectorization. I.e. isolate dependences 970 // into separate loop that would otherwise inhibit vectorization. This is 971 // currently only performed for loops marked with the metadata 972 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 973 OptimizePM.addPass(LoopDistributePass()); 974 975 // Populates the VFABI attribute with the scalar-to-vector mappings 976 // from the TargetLibraryInfo. 977 OptimizePM.addPass(InjectTLIMappings()); 978 979 // Now run the core loop vectorizer. 980 OptimizePM.addPass(LoopVectorizePass( 981 LoopVectorizeOptions(!PTO.LoopInterleaving, !PTO.LoopVectorization))); 982 983 // Enhance/cleanup vector code. 984 OptimizePM.addPass(VectorCombinePass()); 985 OptimizePM.addPass(EarlyCSEPass()); 986 987 // Eliminate loads by forwarding stores from the previous iteration to loads 988 // of the current iteration. 989 OptimizePM.addPass(LoopLoadEliminationPass()); 990 991 // Cleanup after the loop optimization passes. 992 OptimizePM.addPass(InstCombinePass()); 993 994 // Now that we've formed fast to execute loop structures, we do further 995 // optimizations. These are run afterward as they might block doing complex 996 // analyses and transforms such as what are needed for loop vectorization. 997 998 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 999 // GVN, loop transforms, and others have already run, so it's now better to 1000 // convert to more optimized IR using more aggressive simplify CFG options. 1001 // The extra sinking transform can create larger basic blocks, so do this 1002 // before SLP vectorization. 1003 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions(). 1004 forwardSwitchCondToPhi(true). 1005 convertSwitchToLookupTable(true). 1006 needCanonicalLoops(false). 1007 sinkCommonInsts(true))); 1008 1009 // Optimize parallel scalar instruction chains into SIMD instructions. 1010 if (PTO.SLPVectorization) 1011 OptimizePM.addPass(SLPVectorizerPass()); 1012 1013 OptimizePM.addPass(InstCombinePass()); 1014 1015 // Unroll small loops to hide loop backedge latency and saturate any parallel 1016 // execution resources of an out-of-order processor. We also then need to 1017 // clean up redundancies and loop invariant code. 1018 // FIXME: It would be really good to use a loop-integrated instruction 1019 // combiner for cleanup here so that the unrolling and LICM can be pipelined 1020 // across the loop nests. 1021 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 1022 if (EnableUnrollAndJam && PTO.LoopUnrolling) { 1023 OptimizePM.addPass(LoopUnrollAndJamPass(Level.getSpeedupLevel())); 1024 } 1025 OptimizePM.addPass(LoopUnrollPass(LoopUnrollOptions( 1026 Level.getSpeedupLevel(), /*OnlyWhenForced=*/!PTO.LoopUnrolling, 1027 PTO.ForgetAllSCEVInLoopUnroll))); 1028 OptimizePM.addPass(WarnMissedTransformationsPass()); 1029 OptimizePM.addPass(InstCombinePass()); 1030 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 1031 OptimizePM.addPass(createFunctionToLoopPassAdaptor( 1032 LICMPass(PTO.LicmMssaOptCap, PTO.LicmMssaNoAccForPromotionCap), 1033 EnableMSSALoopDependency, DebugLogging)); 1034 1035 // Now that we've vectorized and unrolled loops, we may have more refined 1036 // alignment information, try to re-derive it here. 1037 OptimizePM.addPass(AlignmentFromAssumptionsPass()); 1038 1039 // Split out cold code. Splitting is done late to avoid hiding context from 1040 // other optimizations and inadvertently regressing performance. The tradeoff 1041 // is that this has a higher code size cost than splitting early. 1042 if (EnableHotColdSplit && !LTOPreLink) 1043 MPM.addPass(HotColdSplittingPass()); 1044 1045 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 1046 // canonicalization pass that enables other optimizations. As a result, 1047 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 1048 // result too early. 1049 OptimizePM.addPass(LoopSinkPass()); 1050 1051 // And finally clean up LCSSA form before generating code. 1052 OptimizePM.addPass(InstSimplifyPass()); 1053 1054 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 1055 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 1056 // flattening of blocks. 1057 OptimizePM.addPass(DivRemPairsPass()); 1058 1059 // LoopSink (and other loop passes since the last simplifyCFG) might have 1060 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 1061 OptimizePM.addPass(SimplifyCFGPass()); 1062 1063 // Optimize PHIs by speculating around them when profitable. Note that this 1064 // pass needs to be run after any PRE or similar pass as it is essentially 1065 // inserting redundancies into the program. This even includes SimplifyCFG. 1066 OptimizePM.addPass(SpeculateAroundPHIsPass()); 1067 1068 if (PTO.Coroutines) 1069 OptimizePM.addPass(CoroCleanupPass()); 1070 1071 for (auto &C : OptimizerLastEPCallbacks) 1072 C(OptimizePM, Level); 1073 1074 // Add the core optimizing pipeline. 1075 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM))); 1076 1077 if (PTO.CallGraphProfile) 1078 MPM.addPass(CGProfilePass()); 1079 1080 // Now we need to do some global optimization transforms. 1081 // FIXME: It would seem like these should come first in the optimization 1082 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird 1083 // ordering here. 1084 MPM.addPass(GlobalDCEPass()); 1085 MPM.addPass(ConstantMergePass()); 1086 1087 return MPM; 1088 } 1089 1090 ModulePassManager 1091 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level, 1092 bool DebugLogging, bool LTOPreLink) { 1093 assert(Level != OptimizationLevel::O0 && 1094 "Must request optimizations for the default pipeline!"); 1095 1096 ModulePassManager MPM(DebugLogging); 1097 1098 // Force any function attributes we want the rest of the pipeline to observe. 1099 MPM.addPass(ForceFunctionAttrsPass()); 1100 1101 // Apply module pipeline start EP callback. 1102 for (auto &C : PipelineStartEPCallbacks) 1103 C(MPM); 1104 1105 if (PGOOpt && PGOOpt->SamplePGOSupport) 1106 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1107 1108 // Add the core simplification pipeline. 1109 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None, 1110 DebugLogging)); 1111 1112 // Now add the optimization pipeline. 1113 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging, LTOPreLink)); 1114 1115 return MPM; 1116 } 1117 1118 ModulePassManager 1119 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level, 1120 bool DebugLogging) { 1121 assert(Level != OptimizationLevel::O0 && 1122 "Must request optimizations for the default pipeline!"); 1123 1124 ModulePassManager MPM(DebugLogging); 1125 1126 // Force any function attributes we want the rest of the pipeline to observe. 1127 MPM.addPass(ForceFunctionAttrsPass()); 1128 1129 if (PGOOpt && PGOOpt->SamplePGOSupport) 1130 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 1131 1132 // Apply module pipeline start EP callback. 1133 for (auto &C : PipelineStartEPCallbacks) 1134 C(MPM); 1135 1136 // If we are planning to perform ThinLTO later, we don't bloat the code with 1137 // unrolling/vectorization/... now. Just simplify the module as much as we 1138 // can. 1139 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink, 1140 DebugLogging)); 1141 1142 // Run partial inlining pass to partially inline functions that have 1143 // large bodies. 1144 // FIXME: It isn't clear whether this is really the right place to run this 1145 // in ThinLTO. Because there is another canonicalization and simplification 1146 // phase that will run after the thin link, running this here ends up with 1147 // less information than will be available later and it may grow functions in 1148 // ways that aren't beneficial. 1149 if (RunPartialInlining) 1150 MPM.addPass(PartialInlinerPass()); 1151 1152 // Reduce the size of the IR as much as possible. 1153 MPM.addPass(GlobalOptPass()); 1154 1155 // Module simplification splits coroutines, but does not fully clean up 1156 // coroutine intrinsics. To ensure ThinLTO optimization passes don't trip up 1157 // on these, we schedule the cleanup here. 1158 if (PTO.Coroutines) 1159 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1160 1161 return MPM; 1162 } 1163 1164 ModulePassManager PassBuilder::buildThinLTODefaultPipeline( 1165 OptimizationLevel Level, bool DebugLogging, 1166 const ModuleSummaryIndex *ImportSummary) { 1167 ModulePassManager MPM(DebugLogging); 1168 1169 if (ImportSummary) { 1170 // These passes import type identifier resolutions for whole-program 1171 // devirtualization and CFI. They must run early because other passes may 1172 // disturb the specific instruction patterns that these passes look for, 1173 // creating dependencies on resolutions that may not appear in the summary. 1174 // 1175 // For example, GVN may transform the pattern assume(type.test) appearing in 1176 // two basic blocks into assume(phi(type.test, type.test)), which would 1177 // transform a dependency on a WPD resolution into a dependency on a type 1178 // identifier resolution for CFI. 1179 // 1180 // Also, WPD has access to more precise information than ICP and can 1181 // devirtualize more effectively, so it should operate on the IR first. 1182 // 1183 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1184 // metadata and intrinsics. 1185 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary)); 1186 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary)); 1187 } 1188 1189 if (Level == OptimizationLevel::O0) 1190 return MPM; 1191 1192 // Force any function attributes we want the rest of the pipeline to observe. 1193 MPM.addPass(ForceFunctionAttrsPass()); 1194 1195 // Add the core simplification pipeline. 1196 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink, 1197 DebugLogging)); 1198 1199 // Now add the optimization pipeline. 1200 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging)); 1201 1202 return MPM; 1203 } 1204 1205 ModulePassManager 1206 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level, 1207 bool DebugLogging) { 1208 assert(Level != OptimizationLevel::O0 && 1209 "Must request optimizations for the default pipeline!"); 1210 // FIXME: We should use a customized pre-link pipeline! 1211 return buildPerModuleDefaultPipeline(Level, DebugLogging, 1212 /* LTOPreLink */ true); 1213 } 1214 1215 ModulePassManager 1216 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, 1217 ModuleSummaryIndex *ExportSummary) { 1218 ModulePassManager MPM(DebugLogging); 1219 1220 if (Level == OptimizationLevel::O0) { 1221 // The WPD and LowerTypeTest passes need to run at -O0 to lower type 1222 // metadata and intrinsics. 1223 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1224 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1225 return MPM; 1226 } 1227 1228 if (PGOOpt && PGOOpt->Action == PGOOptions::SampleUse) { 1229 // Load sample profile before running the LTO optimization pipeline. 1230 MPM.addPass(SampleProfileLoaderPass(PGOOpt->ProfileFile, 1231 PGOOpt->ProfileRemappingFile, 1232 false /* ThinLTOPhase::PreLink */)); 1233 // Cache ProfileSummaryAnalysis once to avoid the potential need to insert 1234 // RequireAnalysisPass for PSI before subsequent non-module passes. 1235 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 1236 } 1237 1238 // Remove unused virtual tables to improve the quality of code generated by 1239 // whole-program devirtualization and bitset lowering. 1240 MPM.addPass(GlobalDCEPass()); 1241 1242 // Force any function attributes we want the rest of the pipeline to observe. 1243 MPM.addPass(ForceFunctionAttrsPass()); 1244 1245 // Do basic inference of function attributes from known properties of system 1246 // libraries and other oracles. 1247 MPM.addPass(InferFunctionAttrsPass()); 1248 1249 if (Level.getSpeedupLevel() > 1) { 1250 FunctionPassManager EarlyFPM(DebugLogging); 1251 EarlyFPM.addPass(CallSiteSplittingPass()); 1252 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 1253 1254 // Indirect call promotion. This should promote all the targets that are 1255 // left by the earlier promotion pass that promotes intra-module targets. 1256 // This two-step promotion is to save the compile time. For LTO, it should 1257 // produce the same result as if we only do promotion here. 1258 MPM.addPass(PGOIndirectCallPromotion( 1259 true /* InLTO */, PGOOpt && PGOOpt->Action == PGOOptions::SampleUse)); 1260 // Propagate constants at call sites into the functions they call. This 1261 // opens opportunities for globalopt (and inlining) by substituting function 1262 // pointers passed as arguments to direct uses of functions. 1263 MPM.addPass(IPSCCPPass()); 1264 1265 // Attach metadata to indirect call sites indicating the set of functions 1266 // they may target at run-time. This should follow IPSCCP. 1267 MPM.addPass(CalledValuePropagationPass()); 1268 } 1269 1270 // Now deduce any function attributes based in the current code. 1271 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1272 PostOrderFunctionAttrsPass())); 1273 1274 // Do RPO function attribute inference across the module to forward-propagate 1275 // attributes where applicable. 1276 // FIXME: Is this really an optimization rather than a canonicalization? 1277 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1278 1279 // Use in-range annotations on GEP indices to split globals where beneficial. 1280 MPM.addPass(GlobalSplitPass()); 1281 1282 // Run whole program optimization of virtual call when the list of callees 1283 // is fixed. 1284 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1285 1286 // Stop here at -O1. 1287 if (Level == OptimizationLevel::O1) { 1288 // The LowerTypeTestsPass needs to run to lower type metadata and the 1289 // type.test intrinsics. The pass does nothing if CFI is disabled. 1290 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1291 return MPM; 1292 } 1293 1294 // Optimize globals to try and fold them into constants. 1295 MPM.addPass(GlobalOptPass()); 1296 1297 // Promote any localized globals to SSA registers. 1298 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 1299 1300 // Linking modules together can lead to duplicate global constant, only 1301 // keep one copy of each constant. 1302 MPM.addPass(ConstantMergePass()); 1303 1304 // Remove unused arguments from functions. 1305 MPM.addPass(DeadArgumentEliminationPass()); 1306 1307 // Reduce the code after globalopt and ipsccp. Both can open up significant 1308 // simplification opportunities, and both can propagate functions through 1309 // function pointers. When this happens, we often have to resolve varargs 1310 // calls, etc, so let instcombine do this. 1311 FunctionPassManager PeepholeFPM(DebugLogging); 1312 if (Level == OptimizationLevel::O3) 1313 PeepholeFPM.addPass(AggressiveInstCombinePass()); 1314 PeepholeFPM.addPass(InstCombinePass()); 1315 invokePeepholeEPCallbacks(PeepholeFPM, Level); 1316 1317 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM))); 1318 1319 // Note: historically, the PruneEH pass was run first to deduce nounwind and 1320 // generally clean up exception handling overhead. It isn't clear this is 1321 // valuable as the inliner doesn't currently care whether it is inlining an 1322 // invoke or a call. 1323 // Run the inliner now. 1324 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1325 InlinerPass(getInlineParamsFromOptLevel(Level)))); 1326 1327 // Optimize globals again after we ran the inliner. 1328 MPM.addPass(GlobalOptPass()); 1329 1330 // Garbage collect dead functions. 1331 // FIXME: Add ArgumentPromotion pass after once it's ported. 1332 MPM.addPass(GlobalDCEPass()); 1333 1334 FunctionPassManager FPM(DebugLogging); 1335 // The IPO Passes may leave cruft around. Clean up after them. 1336 FPM.addPass(InstCombinePass()); 1337 invokePeepholeEPCallbacks(FPM, Level); 1338 1339 FPM.addPass(JumpThreadingPass()); 1340 1341 // Do a post inline PGO instrumentation and use pass. This is a context 1342 // sensitive PGO pass. 1343 if (PGOOpt) { 1344 if (PGOOpt->CSAction == PGOOptions::CSIRInstr) 1345 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ true, 1346 /* IsCS */ true, PGOOpt->CSProfileGenFile, 1347 PGOOpt->ProfileRemappingFile); 1348 else if (PGOOpt->CSAction == PGOOptions::CSIRUse) 1349 addPGOInstrPasses(MPM, DebugLogging, Level, /* RunProfileGen */ false, 1350 /* IsCS */ true, PGOOpt->ProfileFile, 1351 PGOOpt->ProfileRemappingFile); 1352 } 1353 1354 // Break up allocas 1355 FPM.addPass(SROA()); 1356 1357 // LTO provides additional opportunities for tailcall elimination due to 1358 // link-time inlining, and visibility of nocapture attribute. 1359 FPM.addPass(TailCallElimPass()); 1360 1361 // Run a few AA driver optimizations here and now to cleanup the code. 1362 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1363 1364 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1365 PostOrderFunctionAttrsPass())); 1366 // FIXME: here we run IP alias analysis in the legacy PM. 1367 1368 FunctionPassManager MainFPM; 1369 1370 // FIXME: once we fix LoopPass Manager, add LICM here. 1371 // FIXME: once we provide support for enabling MLSM, add it here. 1372 if (RunNewGVN) 1373 MainFPM.addPass(NewGVNPass()); 1374 else 1375 MainFPM.addPass(GVN()); 1376 1377 // Remove dead memcpy()'s. 1378 MainFPM.addPass(MemCpyOptPass()); 1379 1380 // Nuke dead stores. 1381 MainFPM.addPass(DSEPass()); 1382 1383 // FIXME: at this point, we run a bunch of loop passes: 1384 // indVarSimplify, loopDeletion, loopInterchange, loopUnroll, 1385 // loopVectorize. Enable them once the remaining issue with LPM 1386 // are sorted out. 1387 1388 MainFPM.addPass(InstCombinePass()); 1389 MainFPM.addPass(SimplifyCFGPass()); 1390 MainFPM.addPass(SCCPPass()); 1391 MainFPM.addPass(InstCombinePass()); 1392 MainFPM.addPass(BDCEPass()); 1393 1394 // FIXME: We may want to run SLPVectorizer here. 1395 // After vectorization, assume intrinsics may tell us more 1396 // about pointer alignments. 1397 #if 0 1398 MainFPM.add(AlignmentFromAssumptionsPass()); 1399 #endif 1400 1401 // FIXME: Conditionally run LoadCombine here, after it's ported 1402 // (in case we still have this pass, given its questionable usefulness). 1403 1404 MainFPM.addPass(InstCombinePass()); 1405 invokePeepholeEPCallbacks(MainFPM, Level); 1406 MainFPM.addPass(JumpThreadingPass()); 1407 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM))); 1408 1409 // Create a function that performs CFI checks for cross-DSO calls with 1410 // targets in the current module. 1411 MPM.addPass(CrossDSOCFIPass()); 1412 1413 // Lower type metadata and the type.test intrinsic. This pass supports 1414 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs 1415 // to be run at link time if CFI is enabled. This pass does nothing if 1416 // CFI is disabled. 1417 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1418 1419 // Enable splitting late in the FullLTO post-link pipeline. This is done in 1420 // the same stage in the old pass manager (\ref addLateLTOOptimizationPasses). 1421 if (EnableHotColdSplit) 1422 MPM.addPass(HotColdSplittingPass()); 1423 1424 // Add late LTO optimization passes. 1425 // Delete basic blocks, which optimization passes may have killed. 1426 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass())); 1427 1428 // Drop bodies of available eternally objects to improve GlobalDCE. 1429 MPM.addPass(EliminateAvailableExternallyPass()); 1430 1431 // Now that we have optimized the program, discard unreachable functions. 1432 MPM.addPass(GlobalDCEPass()); 1433 1434 // FIXME: Maybe enable MergeFuncs conditionally after it's ported. 1435 return MPM; 1436 } 1437 1438 AAManager PassBuilder::buildDefaultAAPipeline() { 1439 AAManager AA; 1440 1441 // The order in which these are registered determines their priority when 1442 // being queried. 1443 1444 // First we register the basic alias analysis that provides the majority of 1445 // per-function local AA logic. This is a stateless, on-demand local set of 1446 // AA techniques. 1447 AA.registerFunctionAnalysis<BasicAA>(); 1448 1449 // Next we query fast, specialized alias analyses that wrap IR-embedded 1450 // information about aliasing. 1451 AA.registerFunctionAnalysis<ScopedNoAliasAA>(); 1452 AA.registerFunctionAnalysis<TypeBasedAA>(); 1453 1454 // Add support for querying global aliasing information when available. 1455 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module 1456 // analysis, all that the `AAManager` can do is query for any *cached* 1457 // results from `GlobalsAA` through a readonly proxy. 1458 AA.registerModuleAnalysis<GlobalsAA>(); 1459 1460 return AA; 1461 } 1462 1463 static Optional<int> parseRepeatPassName(StringRef Name) { 1464 if (!Name.consume_front("repeat<") || !Name.consume_back(">")) 1465 return None; 1466 int Count; 1467 if (Name.getAsInteger(0, Count) || Count <= 0) 1468 return None; 1469 return Count; 1470 } 1471 1472 static Optional<int> parseDevirtPassName(StringRef Name) { 1473 if (!Name.consume_front("devirt<") || !Name.consume_back(">")) 1474 return None; 1475 int Count; 1476 if (Name.getAsInteger(0, Count) || Count <= 0) 1477 return None; 1478 return Count; 1479 } 1480 1481 static bool checkParametrizedPassName(StringRef Name, StringRef PassName) { 1482 if (!Name.consume_front(PassName)) 1483 return false; 1484 // normal pass name w/o parameters == default parameters 1485 if (Name.empty()) 1486 return true; 1487 return Name.startswith("<") && Name.endswith(">"); 1488 } 1489 1490 namespace { 1491 1492 /// This performs customized parsing of pass name with parameters. 1493 /// 1494 /// We do not need parametrization of passes in textual pipeline very often, 1495 /// yet on a rare occasion ability to specify parameters right there can be 1496 /// useful. 1497 /// 1498 /// \p Name - parameterized specification of a pass from a textual pipeline 1499 /// is a string in a form of : 1500 /// PassName '<' parameter-list '>' 1501 /// 1502 /// Parameter list is being parsed by the parser callable argument, \p Parser, 1503 /// It takes a string-ref of parameters and returns either StringError or a 1504 /// parameter list in a form of a custom parameters type, all wrapped into 1505 /// Expected<> template class. 1506 /// 1507 template <typename ParametersParseCallableT> 1508 auto parsePassParameters(ParametersParseCallableT &&Parser, StringRef Name, 1509 StringRef PassName) -> decltype(Parser(StringRef{})) { 1510 using ParametersT = typename decltype(Parser(StringRef{}))::value_type; 1511 1512 StringRef Params = Name; 1513 if (!Params.consume_front(PassName)) { 1514 assert(false && 1515 "unable to strip pass name from parametrized pass specification"); 1516 } 1517 if (Params.empty()) 1518 return ParametersT{}; 1519 if (!Params.consume_front("<") || !Params.consume_back(">")) { 1520 assert(false && "invalid format for parametrized pass name"); 1521 } 1522 1523 Expected<ParametersT> Result = Parser(Params); 1524 assert((Result || Result.template errorIsA<StringError>()) && 1525 "Pass parameter parser can only return StringErrors."); 1526 return Result; 1527 } 1528 1529 /// Parser of parameters for LoopUnroll pass. 1530 Expected<LoopUnrollOptions> parseLoopUnrollOptions(StringRef Params) { 1531 LoopUnrollOptions UnrollOpts; 1532 while (!Params.empty()) { 1533 StringRef ParamName; 1534 std::tie(ParamName, Params) = Params.split(';'); 1535 int OptLevel = StringSwitch<int>(ParamName) 1536 .Case("O0", 0) 1537 .Case("O1", 1) 1538 .Case("O2", 2) 1539 .Case("O3", 3) 1540 .Default(-1); 1541 if (OptLevel >= 0) { 1542 UnrollOpts.setOptLevel(OptLevel); 1543 continue; 1544 } 1545 if (ParamName.consume_front("full-unroll-max=")) { 1546 int Count; 1547 if (ParamName.getAsInteger(0, Count)) 1548 return make_error<StringError>( 1549 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(), 1550 inconvertibleErrorCode()); 1551 UnrollOpts.setFullUnrollMaxCount(Count); 1552 continue; 1553 } 1554 1555 bool Enable = !ParamName.consume_front("no-"); 1556 if (ParamName == "partial") { 1557 UnrollOpts.setPartial(Enable); 1558 } else if (ParamName == "peeling") { 1559 UnrollOpts.setPeeling(Enable); 1560 } else if (ParamName == "profile-peeling") { 1561 UnrollOpts.setProfileBasedPeeling(Enable); 1562 } else if (ParamName == "runtime") { 1563 UnrollOpts.setRuntime(Enable); 1564 } else if (ParamName == "upperbound") { 1565 UnrollOpts.setUpperBound(Enable); 1566 } else { 1567 return make_error<StringError>( 1568 formatv("invalid LoopUnrollPass parameter '{0}' ", ParamName).str(), 1569 inconvertibleErrorCode()); 1570 } 1571 } 1572 return UnrollOpts; 1573 } 1574 1575 Expected<MemorySanitizerOptions> parseMSanPassOptions(StringRef Params) { 1576 MemorySanitizerOptions Result; 1577 while (!Params.empty()) { 1578 StringRef ParamName; 1579 std::tie(ParamName, Params) = Params.split(';'); 1580 1581 if (ParamName == "recover") { 1582 Result.Recover = true; 1583 } else if (ParamName == "kernel") { 1584 Result.Kernel = true; 1585 } else if (ParamName.consume_front("track-origins=")) { 1586 if (ParamName.getAsInteger(0, Result.TrackOrigins)) 1587 return make_error<StringError>( 1588 formatv("invalid argument to MemorySanitizer pass track-origins " 1589 "parameter: '{0}' ", 1590 ParamName) 1591 .str(), 1592 inconvertibleErrorCode()); 1593 } else { 1594 return make_error<StringError>( 1595 formatv("invalid MemorySanitizer pass parameter '{0}' ", ParamName) 1596 .str(), 1597 inconvertibleErrorCode()); 1598 } 1599 } 1600 return Result; 1601 } 1602 1603 /// Parser of parameters for SimplifyCFG pass. 1604 Expected<SimplifyCFGOptions> parseSimplifyCFGOptions(StringRef Params) { 1605 SimplifyCFGOptions Result; 1606 while (!Params.empty()) { 1607 StringRef ParamName; 1608 std::tie(ParamName, Params) = Params.split(';'); 1609 1610 bool Enable = !ParamName.consume_front("no-"); 1611 if (ParamName == "forward-switch-cond") { 1612 Result.forwardSwitchCondToPhi(Enable); 1613 } else if (ParamName == "switch-to-lookup") { 1614 Result.convertSwitchToLookupTable(Enable); 1615 } else if (ParamName == "keep-loops") { 1616 Result.needCanonicalLoops(Enable); 1617 } else if (ParamName == "sink-common-insts") { 1618 Result.sinkCommonInsts(Enable); 1619 } else if (Enable && ParamName.consume_front("bonus-inst-threshold=")) { 1620 APInt BonusInstThreshold; 1621 if (ParamName.getAsInteger(0, BonusInstThreshold)) 1622 return make_error<StringError>( 1623 formatv("invalid argument to SimplifyCFG pass bonus-threshold " 1624 "parameter: '{0}' ", 1625 ParamName).str(), 1626 inconvertibleErrorCode()); 1627 Result.bonusInstThreshold(BonusInstThreshold.getSExtValue()); 1628 } else { 1629 return make_error<StringError>( 1630 formatv("invalid SimplifyCFG pass parameter '{0}' ", ParamName).str(), 1631 inconvertibleErrorCode()); 1632 } 1633 } 1634 return Result; 1635 } 1636 1637 /// Parser of parameters for LoopVectorize pass. 1638 Expected<LoopVectorizeOptions> parseLoopVectorizeOptions(StringRef Params) { 1639 LoopVectorizeOptions Opts; 1640 while (!Params.empty()) { 1641 StringRef ParamName; 1642 std::tie(ParamName, Params) = Params.split(';'); 1643 1644 bool Enable = !ParamName.consume_front("no-"); 1645 if (ParamName == "interleave-forced-only") { 1646 Opts.setInterleaveOnlyWhenForced(Enable); 1647 } else if (ParamName == "vectorize-forced-only") { 1648 Opts.setVectorizeOnlyWhenForced(Enable); 1649 } else { 1650 return make_error<StringError>( 1651 formatv("invalid LoopVectorize parameter '{0}' ", ParamName).str(), 1652 inconvertibleErrorCode()); 1653 } 1654 } 1655 return Opts; 1656 } 1657 1658 Expected<bool> parseLoopUnswitchOptions(StringRef Params) { 1659 bool Result = false; 1660 while (!Params.empty()) { 1661 StringRef ParamName; 1662 std::tie(ParamName, Params) = Params.split(';'); 1663 1664 bool Enable = !ParamName.consume_front("no-"); 1665 if (ParamName == "nontrivial") { 1666 Result = Enable; 1667 } else { 1668 return make_error<StringError>( 1669 formatv("invalid LoopUnswitch pass parameter '{0}' ", ParamName) 1670 .str(), 1671 inconvertibleErrorCode()); 1672 } 1673 } 1674 return Result; 1675 } 1676 1677 Expected<bool> parseMergedLoadStoreMotionOptions(StringRef Params) { 1678 bool Result = false; 1679 while (!Params.empty()) { 1680 StringRef ParamName; 1681 std::tie(ParamName, Params) = Params.split(';'); 1682 1683 bool Enable = !ParamName.consume_front("no-"); 1684 if (ParamName == "split-footer-bb") { 1685 Result = Enable; 1686 } else { 1687 return make_error<StringError>( 1688 formatv("invalid MergedLoadStoreMotion pass parameter '{0}' ", 1689 ParamName) 1690 .str(), 1691 inconvertibleErrorCode()); 1692 } 1693 } 1694 return Result; 1695 } 1696 1697 Expected<GVNOptions> parseGVNOptions(StringRef Params) { 1698 GVNOptions Result; 1699 while (!Params.empty()) { 1700 StringRef ParamName; 1701 std::tie(ParamName, Params) = Params.split(';'); 1702 1703 bool Enable = !ParamName.consume_front("no-"); 1704 if (ParamName == "pre") { 1705 Result.setPRE(Enable); 1706 } else if (ParamName == "load-pre") { 1707 Result.setLoadPRE(Enable); 1708 } else if (ParamName == "memdep") { 1709 Result.setMemDep(Enable); 1710 } else { 1711 return make_error<StringError>( 1712 formatv("invalid GVN pass parameter '{0}' ", ParamName).str(), 1713 inconvertibleErrorCode()); 1714 } 1715 } 1716 return Result; 1717 } 1718 1719 } // namespace 1720 1721 /// Tests whether a pass name starts with a valid prefix for a default pipeline 1722 /// alias. 1723 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) { 1724 return Name.startswith("default") || Name.startswith("thinlto") || 1725 Name.startswith("lto"); 1726 } 1727 1728 /// Tests whether registered callbacks will accept a given pass name. 1729 /// 1730 /// When parsing a pipeline text, the type of the outermost pipeline may be 1731 /// omitted, in which case the type is automatically determined from the first 1732 /// pass name in the text. This may be a name that is handled through one of the 1733 /// callbacks. We check this through the oridinary parsing callbacks by setting 1734 /// up a dummy PassManager in order to not force the client to also handle this 1735 /// type of query. 1736 template <typename PassManagerT, typename CallbacksT> 1737 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) { 1738 if (!Callbacks.empty()) { 1739 PassManagerT DummyPM; 1740 for (auto &CB : Callbacks) 1741 if (CB(Name, DummyPM, {})) 1742 return true; 1743 } 1744 return false; 1745 } 1746 1747 template <typename CallbacksT> 1748 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) { 1749 // Manually handle aliases for pre-configured pipeline fragments. 1750 if (startsWithDefaultPipelineAliasPrefix(Name)) 1751 return DefaultAliasRegex.match(Name); 1752 1753 // Explicitly handle pass manager names. 1754 if (Name == "module") 1755 return true; 1756 if (Name == "cgscc") 1757 return true; 1758 if (Name == "function") 1759 return true; 1760 1761 // Explicitly handle custom-parsed pass names. 1762 if (parseRepeatPassName(Name)) 1763 return true; 1764 1765 #define MODULE_PASS(NAME, CREATE_PASS) \ 1766 if (Name == NAME) \ 1767 return true; 1768 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 1769 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1770 return true; 1771 #include "PassRegistry.def" 1772 1773 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks); 1774 } 1775 1776 template <typename CallbacksT> 1777 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) { 1778 // Explicitly handle pass manager names. 1779 if (Name == "cgscc") 1780 return true; 1781 if (Name == "function") 1782 return true; 1783 1784 // Explicitly handle custom-parsed pass names. 1785 if (parseRepeatPassName(Name)) 1786 return true; 1787 if (parseDevirtPassName(Name)) 1788 return true; 1789 1790 #define CGSCC_PASS(NAME, CREATE_PASS) \ 1791 if (Name == NAME) \ 1792 return true; 1793 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 1794 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1795 return true; 1796 #include "PassRegistry.def" 1797 1798 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks); 1799 } 1800 1801 template <typename CallbacksT> 1802 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) { 1803 // Explicitly handle pass manager names. 1804 if (Name == "function") 1805 return true; 1806 if (Name == "loop" || Name == "loop-mssa") 1807 return true; 1808 1809 // Explicitly handle custom-parsed pass names. 1810 if (parseRepeatPassName(Name)) 1811 return true; 1812 1813 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 1814 if (Name == NAME) \ 1815 return true; 1816 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \ 1817 if (checkParametrizedPassName(Name, NAME)) \ 1818 return true; 1819 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 1820 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1821 return true; 1822 #include "PassRegistry.def" 1823 1824 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks); 1825 } 1826 1827 template <typename CallbacksT> 1828 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) { 1829 // Explicitly handle pass manager names. 1830 if (Name == "loop" || Name == "loop-mssa") 1831 return true; 1832 1833 // Explicitly handle custom-parsed pass names. 1834 if (parseRepeatPassName(Name)) 1835 return true; 1836 1837 #define LOOP_PASS(NAME, CREATE_PASS) \ 1838 if (Name == NAME) \ 1839 return true; 1840 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \ 1841 if (checkParametrizedPassName(Name, NAME)) \ 1842 return true; 1843 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 1844 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1845 return true; 1846 #include "PassRegistry.def" 1847 1848 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks); 1849 } 1850 1851 Optional<std::vector<PassBuilder::PipelineElement>> 1852 PassBuilder::parsePipelineText(StringRef Text) { 1853 std::vector<PipelineElement> ResultPipeline; 1854 1855 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = { 1856 &ResultPipeline}; 1857 for (;;) { 1858 std::vector<PipelineElement> &Pipeline = *PipelineStack.back(); 1859 size_t Pos = Text.find_first_of(",()"); 1860 Pipeline.push_back({Text.substr(0, Pos), {}}); 1861 1862 // If we have a single terminating name, we're done. 1863 if (Pos == Text.npos) 1864 break; 1865 1866 char Sep = Text[Pos]; 1867 Text = Text.substr(Pos + 1); 1868 if (Sep == ',') 1869 // Just a name ending in a comma, continue. 1870 continue; 1871 1872 if (Sep == '(') { 1873 // Push the inner pipeline onto the stack to continue processing. 1874 PipelineStack.push_back(&Pipeline.back().InnerPipeline); 1875 continue; 1876 } 1877 1878 assert(Sep == ')' && "Bogus separator!"); 1879 // When handling the close parenthesis, we greedily consume them to avoid 1880 // empty strings in the pipeline. 1881 do { 1882 // If we try to pop the outer pipeline we have unbalanced parentheses. 1883 if (PipelineStack.size() == 1) 1884 return None; 1885 1886 PipelineStack.pop_back(); 1887 } while (Text.consume_front(")")); 1888 1889 // Check if we've finished parsing. 1890 if (Text.empty()) 1891 break; 1892 1893 // Otherwise, the end of an inner pipeline always has to be followed by 1894 // a comma, and then we can continue. 1895 if (!Text.consume_front(",")) 1896 return None; 1897 } 1898 1899 if (PipelineStack.size() > 1) 1900 // Unbalanced paretheses. 1901 return None; 1902 1903 assert(PipelineStack.back() == &ResultPipeline && 1904 "Wrong pipeline at the bottom of the stack!"); 1905 return {std::move(ResultPipeline)}; 1906 } 1907 1908 Error PassBuilder::parseModulePass(ModulePassManager &MPM, 1909 const PipelineElement &E, 1910 bool VerifyEachPass, bool DebugLogging) { 1911 auto &Name = E.Name; 1912 auto &InnerPipeline = E.InnerPipeline; 1913 1914 // First handle complex passes like the pass managers which carry pipelines. 1915 if (!InnerPipeline.empty()) { 1916 if (Name == "module") { 1917 ModulePassManager NestedMPM(DebugLogging); 1918 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline, 1919 VerifyEachPass, DebugLogging)) 1920 return Err; 1921 MPM.addPass(std::move(NestedMPM)); 1922 return Error::success(); 1923 } 1924 if (Name == "cgscc") { 1925 CGSCCPassManager CGPM(DebugLogging); 1926 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass, 1927 DebugLogging)) 1928 return Err; 1929 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1930 return Error::success(); 1931 } 1932 if (Name == "function") { 1933 FunctionPassManager FPM(DebugLogging); 1934 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline, 1935 VerifyEachPass, DebugLogging)) 1936 return Err; 1937 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1938 return Error::success(); 1939 } 1940 if (auto Count = parseRepeatPassName(Name)) { 1941 ModulePassManager NestedMPM(DebugLogging); 1942 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline, 1943 VerifyEachPass, DebugLogging)) 1944 return Err; 1945 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM))); 1946 return Error::success(); 1947 } 1948 1949 for (auto &C : ModulePipelineParsingCallbacks) 1950 if (C(Name, MPM, InnerPipeline)) 1951 return Error::success(); 1952 1953 // Normal passes can't have pipelines. 1954 return make_error<StringError>( 1955 formatv("invalid use of '{0}' pass as module pipeline", Name).str(), 1956 inconvertibleErrorCode()); 1957 ; 1958 } 1959 1960 // Manually handle aliases for pre-configured pipeline fragments. 1961 if (startsWithDefaultPipelineAliasPrefix(Name)) { 1962 SmallVector<StringRef, 3> Matches; 1963 if (!DefaultAliasRegex.match(Name, &Matches)) 1964 return make_error<StringError>( 1965 formatv("unknown default pipeline alias '{0}'", Name).str(), 1966 inconvertibleErrorCode()); 1967 1968 assert(Matches.size() == 3 && "Must capture two matched strings!"); 1969 1970 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2]) 1971 .Case("O0", OptimizationLevel::O0) 1972 .Case("O1", OptimizationLevel::O1) 1973 .Case("O2", OptimizationLevel::O2) 1974 .Case("O3", OptimizationLevel::O3) 1975 .Case("Os", OptimizationLevel::Os) 1976 .Case("Oz", OptimizationLevel::Oz); 1977 if (L == OptimizationLevel::O0) { 1978 // Add instrumentation PGO passes -- at O0 we can still do PGO. 1979 if (PGOOpt && Matches[1] != "thinlto" && 1980 (PGOOpt->Action == PGOOptions::IRInstr || 1981 PGOOpt->Action == PGOOptions::IRUse)) 1982 addPGOInstrPassesForO0( 1983 MPM, DebugLogging, 1984 /* RunProfileGen */ (PGOOpt->Action == PGOOptions::IRInstr), 1985 /* IsCS */ false, PGOOpt->ProfileFile, 1986 PGOOpt->ProfileRemappingFile); 1987 1988 // For IR that makes use of coroutines intrinsics, coroutine passes must 1989 // be run, even at -O0. 1990 if (PTO.Coroutines) { 1991 MPM.addPass(createModuleToFunctionPassAdaptor(CoroEarlyPass())); 1992 1993 CGSCCPassManager CGPM(DebugLogging); 1994 CGPM.addPass(CoroSplitPass()); 1995 CGPM.addPass(createCGSCCToFunctionPassAdaptor(CoroElidePass())); 1996 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1997 1998 MPM.addPass(createModuleToFunctionPassAdaptor(CoroCleanupPass())); 1999 } 2000 2001 // Do nothing else at all! 2002 return Error::success(); 2003 } 2004 2005 // This is consistent with old pass manager invoked via opt, but 2006 // inconsistent with clang. Clang doesn't enable loop vectorization 2007 // but does enable slp vectorization at Oz. 2008 PTO.LoopVectorization = 2009 L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz; 2010 PTO.SLPVectorization = 2011 L.getSpeedupLevel() > 1 && L != OptimizationLevel::Oz; 2012 2013 if (Matches[1] == "default") { 2014 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging)); 2015 } else if (Matches[1] == "thinlto-pre-link") { 2016 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging)); 2017 } else if (Matches[1] == "thinlto") { 2018 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr)); 2019 } else if (Matches[1] == "lto-pre-link") { 2020 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging)); 2021 } else { 2022 assert(Matches[1] == "lto" && "Not one of the matched options!"); 2023 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr)); 2024 } 2025 return Error::success(); 2026 } 2027 2028 // Finally expand the basic registered passes from the .inc file. 2029 #define MODULE_PASS(NAME, CREATE_PASS) \ 2030 if (Name == NAME) { \ 2031 MPM.addPass(CREATE_PASS); \ 2032 return Error::success(); \ 2033 } 2034 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 2035 if (Name == "require<" NAME ">") { \ 2036 MPM.addPass( \ 2037 RequireAnalysisPass< \ 2038 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \ 2039 return Error::success(); \ 2040 } \ 2041 if (Name == "invalidate<" NAME ">") { \ 2042 MPM.addPass(InvalidateAnalysisPass< \ 2043 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2044 return Error::success(); \ 2045 } 2046 #include "PassRegistry.def" 2047 2048 for (auto &C : ModulePipelineParsingCallbacks) 2049 if (C(Name, MPM, InnerPipeline)) 2050 return Error::success(); 2051 return make_error<StringError>( 2052 formatv("unknown module pass '{0}'", Name).str(), 2053 inconvertibleErrorCode()); 2054 } 2055 2056 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM, 2057 const PipelineElement &E, bool VerifyEachPass, 2058 bool DebugLogging) { 2059 auto &Name = E.Name; 2060 auto &InnerPipeline = E.InnerPipeline; 2061 2062 // First handle complex passes like the pass managers which carry pipelines. 2063 if (!InnerPipeline.empty()) { 2064 if (Name == "cgscc") { 2065 CGSCCPassManager NestedCGPM(DebugLogging); 2066 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 2067 VerifyEachPass, DebugLogging)) 2068 return Err; 2069 // Add the nested pass manager with the appropriate adaptor. 2070 CGPM.addPass(std::move(NestedCGPM)); 2071 return Error::success(); 2072 } 2073 if (Name == "function") { 2074 FunctionPassManager FPM(DebugLogging); 2075 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline, 2076 VerifyEachPass, DebugLogging)) 2077 return Err; 2078 // Add the nested pass manager with the appropriate adaptor. 2079 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 2080 return Error::success(); 2081 } 2082 if (auto Count = parseRepeatPassName(Name)) { 2083 CGSCCPassManager NestedCGPM(DebugLogging); 2084 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 2085 VerifyEachPass, DebugLogging)) 2086 return Err; 2087 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM))); 2088 return Error::success(); 2089 } 2090 if (auto MaxRepetitions = parseDevirtPassName(Name)) { 2091 CGSCCPassManager NestedCGPM(DebugLogging); 2092 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 2093 VerifyEachPass, DebugLogging)) 2094 return Err; 2095 CGPM.addPass( 2096 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions)); 2097 return Error::success(); 2098 } 2099 2100 for (auto &C : CGSCCPipelineParsingCallbacks) 2101 if (C(Name, CGPM, InnerPipeline)) 2102 return Error::success(); 2103 2104 // Normal passes can't have pipelines. 2105 return make_error<StringError>( 2106 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(), 2107 inconvertibleErrorCode()); 2108 } 2109 2110 // Now expand the basic registered passes from the .inc file. 2111 #define CGSCC_PASS(NAME, CREATE_PASS) \ 2112 if (Name == NAME) { \ 2113 CGPM.addPass(CREATE_PASS); \ 2114 return Error::success(); \ 2115 } 2116 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 2117 if (Name == "require<" NAME ">") { \ 2118 CGPM.addPass(RequireAnalysisPass< \ 2119 std::remove_reference<decltype(CREATE_PASS)>::type, \ 2120 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \ 2121 CGSCCUpdateResult &>()); \ 2122 return Error::success(); \ 2123 } \ 2124 if (Name == "invalidate<" NAME ">") { \ 2125 CGPM.addPass(InvalidateAnalysisPass< \ 2126 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2127 return Error::success(); \ 2128 } 2129 #include "PassRegistry.def" 2130 2131 for (auto &C : CGSCCPipelineParsingCallbacks) 2132 if (C(Name, CGPM, InnerPipeline)) 2133 return Error::success(); 2134 return make_error<StringError>( 2135 formatv("unknown cgscc pass '{0}'", Name).str(), 2136 inconvertibleErrorCode()); 2137 } 2138 2139 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM, 2140 const PipelineElement &E, 2141 bool VerifyEachPass, bool DebugLogging) { 2142 auto &Name = E.Name; 2143 auto &InnerPipeline = E.InnerPipeline; 2144 2145 // First handle complex passes like the pass managers which carry pipelines. 2146 if (!InnerPipeline.empty()) { 2147 if (Name == "function") { 2148 FunctionPassManager NestedFPM(DebugLogging); 2149 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline, 2150 VerifyEachPass, DebugLogging)) 2151 return Err; 2152 // Add the nested pass manager with the appropriate adaptor. 2153 FPM.addPass(std::move(NestedFPM)); 2154 return Error::success(); 2155 } 2156 if (Name == "loop" || Name == "loop-mssa") { 2157 LoopPassManager LPM(DebugLogging); 2158 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass, 2159 DebugLogging)) 2160 return Err; 2161 // Add the nested pass manager with the appropriate adaptor. 2162 bool UseMemorySSA = (Name == "loop-mssa"); 2163 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM), UseMemorySSA, 2164 DebugLogging)); 2165 return Error::success(); 2166 } 2167 if (auto Count = parseRepeatPassName(Name)) { 2168 FunctionPassManager NestedFPM(DebugLogging); 2169 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline, 2170 VerifyEachPass, DebugLogging)) 2171 return Err; 2172 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM))); 2173 return Error::success(); 2174 } 2175 2176 for (auto &C : FunctionPipelineParsingCallbacks) 2177 if (C(Name, FPM, InnerPipeline)) 2178 return Error::success(); 2179 2180 // Normal passes can't have pipelines. 2181 return make_error<StringError>( 2182 formatv("invalid use of '{0}' pass as function pipeline", Name).str(), 2183 inconvertibleErrorCode()); 2184 } 2185 2186 // Now expand the basic registered passes from the .inc file. 2187 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 2188 if (Name == NAME) { \ 2189 FPM.addPass(CREATE_PASS); \ 2190 return Error::success(); \ 2191 } 2192 #define FUNCTION_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \ 2193 if (checkParametrizedPassName(Name, NAME)) { \ 2194 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2195 if (!Params) \ 2196 return Params.takeError(); \ 2197 FPM.addPass(CREATE_PASS(Params.get())); \ 2198 return Error::success(); \ 2199 } 2200 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 2201 if (Name == "require<" NAME ">") { \ 2202 FPM.addPass( \ 2203 RequireAnalysisPass< \ 2204 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \ 2205 return Error::success(); \ 2206 } \ 2207 if (Name == "invalidate<" NAME ">") { \ 2208 FPM.addPass(InvalidateAnalysisPass< \ 2209 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2210 return Error::success(); \ 2211 } 2212 #include "PassRegistry.def" 2213 2214 for (auto &C : FunctionPipelineParsingCallbacks) 2215 if (C(Name, FPM, InnerPipeline)) 2216 return Error::success(); 2217 return make_error<StringError>( 2218 formatv("unknown function pass '{0}'", Name).str(), 2219 inconvertibleErrorCode()); 2220 } 2221 2222 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E, 2223 bool VerifyEachPass, bool DebugLogging) { 2224 StringRef Name = E.Name; 2225 auto &InnerPipeline = E.InnerPipeline; 2226 2227 // First handle complex passes like the pass managers which carry pipelines. 2228 if (!InnerPipeline.empty()) { 2229 if (Name == "loop") { 2230 LoopPassManager NestedLPM(DebugLogging); 2231 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline, 2232 VerifyEachPass, DebugLogging)) 2233 return Err; 2234 // Add the nested pass manager with the appropriate adaptor. 2235 LPM.addPass(std::move(NestedLPM)); 2236 return Error::success(); 2237 } 2238 if (auto Count = parseRepeatPassName(Name)) { 2239 LoopPassManager NestedLPM(DebugLogging); 2240 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline, 2241 VerifyEachPass, DebugLogging)) 2242 return Err; 2243 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM))); 2244 return Error::success(); 2245 } 2246 2247 for (auto &C : LoopPipelineParsingCallbacks) 2248 if (C(Name, LPM, InnerPipeline)) 2249 return Error::success(); 2250 2251 // Normal passes can't have pipelines. 2252 return make_error<StringError>( 2253 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(), 2254 inconvertibleErrorCode()); 2255 } 2256 2257 // Now expand the basic registered passes from the .inc file. 2258 #define LOOP_PASS(NAME, CREATE_PASS) \ 2259 if (Name == NAME) { \ 2260 LPM.addPass(CREATE_PASS); \ 2261 return Error::success(); \ 2262 } 2263 #define LOOP_PASS_WITH_PARAMS(NAME, CREATE_PASS, PARSER) \ 2264 if (checkParametrizedPassName(Name, NAME)) { \ 2265 auto Params = parsePassParameters(PARSER, Name, NAME); \ 2266 if (!Params) \ 2267 return Params.takeError(); \ 2268 LPM.addPass(CREATE_PASS(Params.get())); \ 2269 return Error::success(); \ 2270 } 2271 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 2272 if (Name == "require<" NAME ">") { \ 2273 LPM.addPass(RequireAnalysisPass< \ 2274 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \ 2275 LoopAnalysisManager, LoopStandardAnalysisResults &, \ 2276 LPMUpdater &>()); \ 2277 return Error::success(); \ 2278 } \ 2279 if (Name == "invalidate<" NAME ">") { \ 2280 LPM.addPass(InvalidateAnalysisPass< \ 2281 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 2282 return Error::success(); \ 2283 } 2284 #include "PassRegistry.def" 2285 2286 for (auto &C : LoopPipelineParsingCallbacks) 2287 if (C(Name, LPM, InnerPipeline)) 2288 return Error::success(); 2289 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(), 2290 inconvertibleErrorCode()); 2291 } 2292 2293 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) { 2294 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 2295 if (Name == NAME) { \ 2296 AA.registerModuleAnalysis< \ 2297 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 2298 return true; \ 2299 } 2300 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 2301 if (Name == NAME) { \ 2302 AA.registerFunctionAnalysis< \ 2303 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 2304 return true; \ 2305 } 2306 #include "PassRegistry.def" 2307 2308 for (auto &C : AAParsingCallbacks) 2309 if (C(Name, AA)) 2310 return true; 2311 return false; 2312 } 2313 2314 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM, 2315 ArrayRef<PipelineElement> Pipeline, 2316 bool VerifyEachPass, 2317 bool DebugLogging) { 2318 for (const auto &Element : Pipeline) { 2319 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging)) 2320 return Err; 2321 // FIXME: No verifier support for Loop passes! 2322 } 2323 return Error::success(); 2324 } 2325 2326 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM, 2327 ArrayRef<PipelineElement> Pipeline, 2328 bool VerifyEachPass, 2329 bool DebugLogging) { 2330 for (const auto &Element : Pipeline) { 2331 if (auto Err = 2332 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging)) 2333 return Err; 2334 if (VerifyEachPass) 2335 FPM.addPass(VerifierPass()); 2336 } 2337 return Error::success(); 2338 } 2339 2340 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM, 2341 ArrayRef<PipelineElement> Pipeline, 2342 bool VerifyEachPass, 2343 bool DebugLogging) { 2344 for (const auto &Element : Pipeline) { 2345 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging)) 2346 return Err; 2347 // FIXME: No verifier support for CGSCC passes! 2348 } 2349 return Error::success(); 2350 } 2351 2352 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM, 2353 FunctionAnalysisManager &FAM, 2354 CGSCCAnalysisManager &CGAM, 2355 ModuleAnalysisManager &MAM) { 2356 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); }); 2357 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); }); 2358 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); }); 2359 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); }); 2360 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); }); 2361 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); }); 2362 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); }); 2363 } 2364 2365 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM, 2366 ArrayRef<PipelineElement> Pipeline, 2367 bool VerifyEachPass, 2368 bool DebugLogging) { 2369 for (const auto &Element : Pipeline) { 2370 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging)) 2371 return Err; 2372 if (VerifyEachPass) 2373 MPM.addPass(VerifierPass()); 2374 } 2375 return Error::success(); 2376 } 2377 2378 // Primary pass pipeline description parsing routine for a \c ModulePassManager 2379 // FIXME: Should this routine accept a TargetMachine or require the caller to 2380 // pre-populate the analysis managers with target-specific stuff? 2381 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM, 2382 StringRef PipelineText, 2383 bool VerifyEachPass, bool DebugLogging) { 2384 auto Pipeline = parsePipelineText(PipelineText); 2385 if (!Pipeline || Pipeline->empty()) 2386 return make_error<StringError>( 2387 formatv("invalid pipeline '{0}'", PipelineText).str(), 2388 inconvertibleErrorCode()); 2389 2390 // If the first name isn't at the module layer, wrap the pipeline up 2391 // automatically. 2392 StringRef FirstName = Pipeline->front().Name; 2393 2394 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) { 2395 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) { 2396 Pipeline = {{"cgscc", std::move(*Pipeline)}}; 2397 } else if (isFunctionPassName(FirstName, 2398 FunctionPipelineParsingCallbacks)) { 2399 Pipeline = {{"function", std::move(*Pipeline)}}; 2400 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) { 2401 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}}; 2402 } else { 2403 for (auto &C : TopLevelPipelineParsingCallbacks) 2404 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging)) 2405 return Error::success(); 2406 2407 // Unknown pass or pipeline name! 2408 auto &InnerPipeline = Pipeline->front().InnerPipeline; 2409 return make_error<StringError>( 2410 formatv("unknown {0} name '{1}'", 2411 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName) 2412 .str(), 2413 inconvertibleErrorCode()); 2414 } 2415 } 2416 2417 if (auto Err = 2418 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging)) 2419 return Err; 2420 return Error::success(); 2421 } 2422 2423 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager 2424 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM, 2425 StringRef PipelineText, 2426 bool VerifyEachPass, bool DebugLogging) { 2427 auto Pipeline = parsePipelineText(PipelineText); 2428 if (!Pipeline || Pipeline->empty()) 2429 return make_error<StringError>( 2430 formatv("invalid pipeline '{0}'", PipelineText).str(), 2431 inconvertibleErrorCode()); 2432 2433 StringRef FirstName = Pipeline->front().Name; 2434 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) 2435 return make_error<StringError>( 2436 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName, 2437 PipelineText) 2438 .str(), 2439 inconvertibleErrorCode()); 2440 2441 if (auto Err = 2442 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging)) 2443 return Err; 2444 return Error::success(); 2445 } 2446 2447 // Primary pass pipeline description parsing routine for a \c 2448 // FunctionPassManager 2449 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM, 2450 StringRef PipelineText, 2451 bool VerifyEachPass, bool DebugLogging) { 2452 auto Pipeline = parsePipelineText(PipelineText); 2453 if (!Pipeline || Pipeline->empty()) 2454 return make_error<StringError>( 2455 formatv("invalid pipeline '{0}'", PipelineText).str(), 2456 inconvertibleErrorCode()); 2457 2458 StringRef FirstName = Pipeline->front().Name; 2459 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks)) 2460 return make_error<StringError>( 2461 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName, 2462 PipelineText) 2463 .str(), 2464 inconvertibleErrorCode()); 2465 2466 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass, 2467 DebugLogging)) 2468 return Err; 2469 return Error::success(); 2470 } 2471 2472 // Primary pass pipeline description parsing routine for a \c LoopPassManager 2473 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM, 2474 StringRef PipelineText, 2475 bool VerifyEachPass, bool DebugLogging) { 2476 auto Pipeline = parsePipelineText(PipelineText); 2477 if (!Pipeline || Pipeline->empty()) 2478 return make_error<StringError>( 2479 formatv("invalid pipeline '{0}'", PipelineText).str(), 2480 inconvertibleErrorCode()); 2481 2482 if (auto Err = 2483 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging)) 2484 return Err; 2485 2486 return Error::success(); 2487 } 2488 2489 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) { 2490 // If the pipeline just consists of the word 'default' just replace the AA 2491 // manager with our default one. 2492 if (PipelineText == "default") { 2493 AA = buildDefaultAAPipeline(); 2494 return Error::success(); 2495 } 2496 2497 while (!PipelineText.empty()) { 2498 StringRef Name; 2499 std::tie(Name, PipelineText) = PipelineText.split(','); 2500 if (!parseAAPassName(AA, Name)) 2501 return make_error<StringError>( 2502 formatv("unknown alias analysis name '{0}'", Name).str(), 2503 inconvertibleErrorCode()); 2504 } 2505 2506 return Error::success(); 2507 } 2508