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