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