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