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