1 //===- Parsing, selection, and construction of pass pipelines -------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 /// \file 10 /// 11 /// This file provides the implementation of the PassBuilder based on our 12 /// static pass registry as well as related functionality. It also provides 13 /// helpers to aid in analyzing, debugging, and testing passes and pass 14 /// pipelines. 15 /// 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Passes/PassBuilder.h" 19 #include "llvm/ADT/StringSwitch.h" 20 #include "llvm/Analysis/AliasAnalysis.h" 21 #include "llvm/Analysis/AliasAnalysisEvaluator.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/DemandedBits.h" 32 #include "llvm/Analysis/DependenceAnalysis.h" 33 #include "llvm/Analysis/DominanceFrontier.h" 34 #include "llvm/Analysis/GlobalsModRef.h" 35 #include "llvm/Analysis/IVUsers.h" 36 #include "llvm/Analysis/LazyCallGraph.h" 37 #include "llvm/Analysis/LazyValueInfo.h" 38 #include "llvm/Analysis/LoopAccessAnalysis.h" 39 #include "llvm/Analysis/LoopInfo.h" 40 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 41 #include "llvm/Analysis/MemorySSA.h" 42 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 43 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 44 #include "llvm/Analysis/PhiValues.h" 45 #include "llvm/Analysis/PostDominators.h" 46 #include "llvm/Analysis/ProfileSummaryInfo.h" 47 #include "llvm/Analysis/RegionInfo.h" 48 #include "llvm/Analysis/ScalarEvolution.h" 49 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 50 #include "llvm/Analysis/ScopedNoAliasAA.h" 51 #include "llvm/Analysis/TargetLibraryInfo.h" 52 #include "llvm/Analysis/TargetTransformInfo.h" 53 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 54 #include "llvm/CodeGen/PreISelIntrinsicLowering.h" 55 #include "llvm/CodeGen/UnreachableBlockElim.h" 56 #include "llvm/IR/Dominators.h" 57 #include "llvm/IR/IRPrintingPasses.h" 58 #include "llvm/IR/PassManager.h" 59 #include "llvm/IR/Verifier.h" 60 #include "llvm/Support/Debug.h" 61 #include "llvm/Support/FormatVariadic.h" 62 #include "llvm/Support/Regex.h" 63 #include "llvm/Target/TargetMachine.h" 64 #include "llvm/Transforms/AggressiveInstCombine/AggressiveInstCombine.h" 65 #include "llvm/Transforms/Instrumentation/CGProfile.h" 66 #include "llvm/Transforms/IPO/AlwaysInliner.h" 67 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 68 #include "llvm/Transforms/IPO/CalledValuePropagation.h" 69 #include "llvm/Transforms/IPO/ConstantMerge.h" 70 #include "llvm/Transforms/IPO/CrossDSOCFI.h" 71 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 72 #include "llvm/Transforms/IPO/ElimAvailExtern.h" 73 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 74 #include "llvm/Transforms/IPO/FunctionAttrs.h" 75 #include "llvm/Transforms/IPO/FunctionImport.h" 76 #include "llvm/Transforms/IPO/GlobalDCE.h" 77 #include "llvm/Transforms/IPO/GlobalOpt.h" 78 #include "llvm/Transforms/IPO/GlobalSplit.h" 79 #include "llvm/Transforms/IPO/HotColdSplitting.h" 80 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 81 #include "llvm/Transforms/IPO/Inliner.h" 82 #include "llvm/Transforms/IPO/Internalize.h" 83 #include "llvm/Transforms/IPO/LowerTypeTests.h" 84 #include "llvm/Transforms/IPO/PartialInlining.h" 85 #include "llvm/Transforms/IPO/SCCP.h" 86 #include "llvm/Transforms/IPO/SampleProfile.h" 87 #include "llvm/Transforms/IPO/StripDeadPrototypes.h" 88 #include "llvm/Transforms/IPO/SyntheticCountsPropagation.h" 89 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 90 #include "llvm/Transforms/InstCombine/InstCombine.h" 91 #include "llvm/Transforms/Instrumentation/BoundsChecking.h" 92 #include "llvm/Transforms/Instrumentation/ControlHeightReduction.h" 93 #include "llvm/Transforms/Instrumentation/GCOVProfiler.h" 94 #include "llvm/Transforms/Instrumentation/InstrProfiling.h" 95 #include "llvm/Transforms/Instrumentation/PGOInstrumentation.h" 96 #include "llvm/Transforms/Scalar/ADCE.h" 97 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 98 #include "llvm/Transforms/Scalar/BDCE.h" 99 #include "llvm/Transforms/Scalar/CallSiteSplitting.h" 100 #include "llvm/Transforms/Scalar/ConstantHoisting.h" 101 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 102 #include "llvm/Transforms/Scalar/DCE.h" 103 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 104 #include "llvm/Transforms/Scalar/DivRemPairs.h" 105 #include "llvm/Transforms/Scalar/EarlyCSE.h" 106 #include "llvm/Transforms/Scalar/Float2Int.h" 107 #include "llvm/Transforms/Scalar/GVN.h" 108 #include "llvm/Transforms/Scalar/GuardWidening.h" 109 #include "llvm/Transforms/Scalar/IVUsersPrinter.h" 110 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 111 #include "llvm/Transforms/Scalar/InductiveRangeCheckElimination.h" 112 #include "llvm/Transforms/Scalar/InstSimplifyPass.h" 113 #include "llvm/Transforms/Scalar/JumpThreading.h" 114 #include "llvm/Transforms/Scalar/LICM.h" 115 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h" 116 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h" 117 #include "llvm/Transforms/Scalar/LoopDeletion.h" 118 #include "llvm/Transforms/Scalar/LoopDistribute.h" 119 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 120 #include "llvm/Transforms/Scalar/LoopInstSimplify.h" 121 #include "llvm/Transforms/Scalar/LoopLoadElimination.h" 122 #include "llvm/Transforms/Scalar/LoopPassManager.h" 123 #include "llvm/Transforms/Scalar/LoopPredication.h" 124 #include "llvm/Transforms/Scalar/LoopRotation.h" 125 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 126 #include "llvm/Transforms/Scalar/LoopSink.h" 127 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 128 #include "llvm/Transforms/Scalar/LoopUnrollAndJamPass.h" 129 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 130 #include "llvm/Transforms/Scalar/LowerAtomic.h" 131 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 132 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h" 133 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 134 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 135 #include "llvm/Transforms/Scalar/NaryReassociate.h" 136 #include "llvm/Transforms/Scalar/NewGVN.h" 137 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h" 138 #include "llvm/Transforms/Scalar/Reassociate.h" 139 #include "llvm/Transforms/Scalar/RewriteStatepointsForGC.h" 140 #include "llvm/Transforms/Scalar/SCCP.h" 141 #include "llvm/Transforms/Scalar/SROA.h" 142 #include "llvm/Transforms/Scalar/SimpleLoopUnswitch.h" 143 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 144 #include "llvm/Transforms/Scalar/Sink.h" 145 #include "llvm/Transforms/Scalar/SpeculateAroundPHIs.h" 146 #include "llvm/Transforms/Scalar/SpeculativeExecution.h" 147 #include "llvm/Transforms/Scalar/TailRecursionElimination.h" 148 #include "llvm/Transforms/Utils/AddDiscriminators.h" 149 #include "llvm/Transforms/Utils/BreakCriticalEdges.h" 150 #include "llvm/Transforms/Utils/EntryExitInstrumenter.h" 151 #include "llvm/Transforms/Utils/LCSSA.h" 152 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" 153 #include "llvm/Transforms/Utils/LoopSimplify.h" 154 #include "llvm/Transforms/Utils/LowerInvoke.h" 155 #include "llvm/Transforms/Utils/Mem2Reg.h" 156 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 157 #include "llvm/Transforms/Utils/SymbolRewriter.h" 158 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 159 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 160 161 using namespace llvm; 162 163 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations", 164 cl::ReallyHidden, cl::init(4)); 165 static cl::opt<bool> 166 RunPartialInlining("enable-npm-partial-inlining", cl::init(false), 167 cl::Hidden, cl::ZeroOrMore, 168 cl::desc("Run Partial inlinining pass")); 169 170 static cl::opt<bool> 171 RunNewGVN("enable-npm-newgvn", cl::init(false), 172 cl::Hidden, cl::ZeroOrMore, 173 cl::desc("Run NewGVN instead of GVN")); 174 175 static cl::opt<bool> EnableEarlyCSEMemSSA( 176 "enable-npm-earlycse-memssa", cl::init(true), cl::Hidden, 177 cl::desc("Enable the EarlyCSE w/ MemorySSA pass for the new PM (default = on)")); 178 179 static cl::opt<bool> EnableGVNHoist( 180 "enable-npm-gvn-hoist", cl::init(false), cl::Hidden, 181 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)")); 182 183 static cl::opt<bool> EnableGVNSink( 184 "enable-npm-gvn-sink", cl::init(false), cl::Hidden, 185 cl::desc("Enable the GVN hoisting pass for the new PM (default = off)")); 186 187 static cl::opt<bool> EnableUnrollAndJam( 188 "enable-npm-unroll-and-jam", cl::init(false), cl::Hidden, 189 cl::desc("Enable the Unroll and Jam pass for the new PM (default = off)")); 190 191 static cl::opt<bool> EnableSyntheticCounts( 192 "enable-npm-synthetic-counts", cl::init(false), cl::Hidden, cl::ZeroOrMore, 193 cl::desc("Run synthetic function entry count generation " 194 "pass")); 195 196 static Regex DefaultAliasRegex( 197 "^(default|thinlto-pre-link|thinlto|lto-pre-link|lto)<(O[0123sz])>$"); 198 199 static cl::opt<bool> 200 EnableCHR("enable-chr-npm", cl::init(true), cl::Hidden, 201 cl::desc("Enable control height reduction optimization (CHR)")); 202 203 extern cl::opt<bool> EnableHotColdSplit; 204 205 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) { 206 switch (Level) { 207 case PassBuilder::O0: 208 case PassBuilder::O1: 209 case PassBuilder::O2: 210 case PassBuilder::O3: 211 return false; 212 213 case PassBuilder::Os: 214 case PassBuilder::Oz: 215 return true; 216 } 217 llvm_unreachable("Invalid optimization level!"); 218 } 219 220 namespace { 221 222 /// No-op module pass which does nothing. 223 struct NoOpModulePass { 224 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) { 225 return PreservedAnalyses::all(); 226 } 227 static StringRef name() { return "NoOpModulePass"; } 228 }; 229 230 /// No-op module analysis. 231 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> { 232 friend AnalysisInfoMixin<NoOpModuleAnalysis>; 233 static AnalysisKey Key; 234 235 public: 236 struct Result {}; 237 Result run(Module &, ModuleAnalysisManager &) { return Result(); } 238 static StringRef name() { return "NoOpModuleAnalysis"; } 239 }; 240 241 /// No-op CGSCC pass which does nothing. 242 struct NoOpCGSCCPass { 243 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &, 244 LazyCallGraph &, CGSCCUpdateResult &UR) { 245 return PreservedAnalyses::all(); 246 } 247 static StringRef name() { return "NoOpCGSCCPass"; } 248 }; 249 250 /// No-op CGSCC analysis. 251 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> { 252 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>; 253 static AnalysisKey Key; 254 255 public: 256 struct Result {}; 257 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) { 258 return Result(); 259 } 260 static StringRef name() { return "NoOpCGSCCAnalysis"; } 261 }; 262 263 /// No-op function pass which does nothing. 264 struct NoOpFunctionPass { 265 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) { 266 return PreservedAnalyses::all(); 267 } 268 static StringRef name() { return "NoOpFunctionPass"; } 269 }; 270 271 /// No-op function analysis. 272 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> { 273 friend AnalysisInfoMixin<NoOpFunctionAnalysis>; 274 static AnalysisKey Key; 275 276 public: 277 struct Result {}; 278 Result run(Function &, FunctionAnalysisManager &) { return Result(); } 279 static StringRef name() { return "NoOpFunctionAnalysis"; } 280 }; 281 282 /// No-op loop pass which does nothing. 283 struct NoOpLoopPass { 284 PreservedAnalyses run(Loop &L, LoopAnalysisManager &, 285 LoopStandardAnalysisResults &, LPMUpdater &) { 286 return PreservedAnalyses::all(); 287 } 288 static StringRef name() { return "NoOpLoopPass"; } 289 }; 290 291 /// No-op loop analysis. 292 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> { 293 friend AnalysisInfoMixin<NoOpLoopAnalysis>; 294 static AnalysisKey Key; 295 296 public: 297 struct Result {}; 298 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) { 299 return Result(); 300 } 301 static StringRef name() { return "NoOpLoopAnalysis"; } 302 }; 303 304 AnalysisKey NoOpModuleAnalysis::Key; 305 AnalysisKey NoOpCGSCCAnalysis::Key; 306 AnalysisKey NoOpFunctionAnalysis::Key; 307 AnalysisKey NoOpLoopAnalysis::Key; 308 309 } // End anonymous namespace. 310 311 void PassBuilder::invokePeepholeEPCallbacks( 312 FunctionPassManager &FPM, PassBuilder::OptimizationLevel Level) { 313 for (auto &C : PeepholeEPCallbacks) 314 C(FPM, Level); 315 } 316 317 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) { 318 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 319 MAM.registerPass([&] { return CREATE_PASS; }); 320 #include "PassRegistry.def" 321 322 for (auto &C : ModuleAnalysisRegistrationCallbacks) 323 C(MAM); 324 } 325 326 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) { 327 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 328 CGAM.registerPass([&] { return CREATE_PASS; }); 329 #include "PassRegistry.def" 330 331 for (auto &C : CGSCCAnalysisRegistrationCallbacks) 332 C(CGAM); 333 } 334 335 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) { 336 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 337 FAM.registerPass([&] { return CREATE_PASS; }); 338 #include "PassRegistry.def" 339 340 for (auto &C : FunctionAnalysisRegistrationCallbacks) 341 C(FAM); 342 } 343 344 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) { 345 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 346 LAM.registerPass([&] { return CREATE_PASS; }); 347 #include "PassRegistry.def" 348 349 for (auto &C : LoopAnalysisRegistrationCallbacks) 350 C(LAM); 351 } 352 353 FunctionPassManager 354 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, 355 ThinLTOPhase Phase, 356 bool DebugLogging) { 357 assert(Level != O0 && "Must request optimizations!"); 358 FunctionPassManager FPM(DebugLogging); 359 360 // Form SSA out of local memory accesses after breaking apart aggregates into 361 // scalars. 362 FPM.addPass(SROA()); 363 364 // Catch trivial redundancies 365 FPM.addPass(EarlyCSEPass(EnableEarlyCSEMemSSA)); 366 367 // Hoisting of scalars and load expressions. 368 if (EnableGVNHoist) 369 FPM.addPass(GVNHoistPass()); 370 371 // Global value numbering based sinking. 372 if (EnableGVNSink) { 373 FPM.addPass(GVNSinkPass()); 374 FPM.addPass(SimplifyCFGPass()); 375 } 376 377 // Speculative execution if the target has divergent branches; otherwise nop. 378 FPM.addPass(SpeculativeExecutionPass()); 379 380 // Optimize based on known information about branches, and cleanup afterward. 381 FPM.addPass(JumpThreadingPass()); 382 FPM.addPass(CorrelatedValuePropagationPass()); 383 FPM.addPass(SimplifyCFGPass()); 384 if (Level == O3) 385 FPM.addPass(AggressiveInstCombinePass()); 386 FPM.addPass(InstCombinePass()); 387 388 if (!isOptimizingForSize(Level)) 389 FPM.addPass(LibCallsShrinkWrapPass()); 390 391 invokePeepholeEPCallbacks(FPM, Level); 392 393 // For PGO use pipeline, try to optimize memory intrinsics such as memcpy 394 // using the size value profile. Don't perform this when optimizing for size. 395 if (PGOOpt && !PGOOpt->ProfileUseFile.empty() && 396 !isOptimizingForSize(Level)) 397 FPM.addPass(PGOMemOPSizeOpt()); 398 399 FPM.addPass(TailCallElimPass()); 400 FPM.addPass(SimplifyCFGPass()); 401 402 // Form canonically associated expression trees, and simplify the trees using 403 // basic mathematical properties. For example, this will form (nearly) 404 // minimal multiplication trees. 405 FPM.addPass(ReassociatePass()); 406 407 // Add the primary loop simplification pipeline. 408 // FIXME: Currently this is split into two loop pass pipelines because we run 409 // some function passes in between them. These can and should be removed 410 // and/or replaced by scheduling the loop pass equivalents in the correct 411 // positions. But those equivalent passes aren't powerful enough yet. 412 // Specifically, `SimplifyCFGPass` and `InstCombinePass` are currently still 413 // used. We have `LoopSimplifyCFGPass` which isn't yet powerful enough yet to 414 // fully replace `SimplifyCFGPass`, and the closest to the other we have is 415 // `LoopInstSimplify`. 416 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging); 417 418 // Simplify the loop body. We do this initially to clean up after other loop 419 // passes run, either when iterating on a loop or on inner loops with 420 // implications on the outer loop. 421 LPM1.addPass(LoopInstSimplifyPass()); 422 LPM1.addPass(LoopSimplifyCFGPass()); 423 424 // Rotate Loop - disable header duplication at -Oz 425 LPM1.addPass(LoopRotatePass(Level != Oz)); 426 LPM1.addPass(LICMPass()); 427 LPM1.addPass(SimpleLoopUnswitchPass()); 428 LPM2.addPass(IndVarSimplifyPass()); 429 LPM2.addPass(LoopIdiomRecognizePass()); 430 431 for (auto &C : LateLoopOptimizationsEPCallbacks) 432 C(LPM2, Level); 433 434 LPM2.addPass(LoopDeletionPass()); 435 // Do not enable unrolling in PreLinkThinLTO phase during sample PGO 436 // because it changes IR to makes profile annotation in back compile 437 // inaccurate. 438 if (Phase != ThinLTOPhase::PreLink || 439 !PGOOpt || PGOOpt->SampleProfileFile.empty()) 440 LPM2.addPass(LoopFullUnrollPass(Level)); 441 442 for (auto &C : LoopOptimizerEndEPCallbacks) 443 C(LPM2, Level); 444 445 // We provide the opt remark emitter pass for LICM to use. We only need to do 446 // this once as it is immutable. 447 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 448 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1), DebugLogging)); 449 FPM.addPass(SimplifyCFGPass()); 450 FPM.addPass(InstCombinePass()); 451 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2), DebugLogging)); 452 453 // Eliminate redundancies. 454 if (Level != O1) { 455 // These passes add substantial compile time so skip them at O1. 456 FPM.addPass(MergedLoadStoreMotionPass()); 457 if (RunNewGVN) 458 FPM.addPass(NewGVNPass()); 459 else 460 FPM.addPass(GVN()); 461 } 462 463 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 464 FPM.addPass(MemCpyOptPass()); 465 466 // Sparse conditional constant propagation. 467 // FIXME: It isn't clear why we do this *after* loop passes rather than 468 // before... 469 FPM.addPass(SCCPPass()); 470 471 // Delete dead bit computations (instcombine runs after to fold away the dead 472 // computations, and then ADCE will run later to exploit any new DCE 473 // opportunities that creates). 474 FPM.addPass(BDCEPass()); 475 476 // Run instcombine after redundancy and dead bit elimination to exploit 477 // opportunities opened up by them. 478 FPM.addPass(InstCombinePass()); 479 invokePeepholeEPCallbacks(FPM, Level); 480 481 // Re-consider control flow based optimizations after redundancy elimination, 482 // redo DCE, etc. 483 FPM.addPass(JumpThreadingPass()); 484 FPM.addPass(CorrelatedValuePropagationPass()); 485 FPM.addPass(DSEPass()); 486 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging)); 487 488 for (auto &C : ScalarOptimizerLateEPCallbacks) 489 C(FPM, Level); 490 491 // Finally, do an expensive DCE pass to catch all the dead code exposed by 492 // the simplifications and basic cleanup after all the simplifications. 493 FPM.addPass(ADCEPass()); 494 FPM.addPass(SimplifyCFGPass()); 495 FPM.addPass(InstCombinePass()); 496 invokePeepholeEPCallbacks(FPM, Level); 497 498 if (EnableCHR && Level == O3 && PGOOpt && 499 (!PGOOpt->ProfileUseFile.empty() || !PGOOpt->SampleProfileFile.empty())) 500 FPM.addPass(ControlHeightReductionPass()); 501 502 return FPM; 503 } 504 505 void PassBuilder::addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging, 506 PassBuilder::OptimizationLevel Level, 507 bool RunProfileGen, 508 std::string ProfileGenFile, 509 std::string ProfileUseFile, 510 std::string ProfileRemappingFile) { 511 // Generally running simplification passes and the inliner with an high 512 // threshold results in smaller executables, but there may be cases where 513 // the size grows, so let's be conservative here and skip this simplification 514 // at -Os/Oz. 515 if (!isOptimizingForSize(Level)) { 516 InlineParams IP; 517 518 // In the old pass manager, this is a cl::opt. Should still this be one? 519 IP.DefaultThreshold = 75; 520 521 // FIXME: The hint threshold has the same value used by the regular inliner. 522 // This should probably be lowered after performance testing. 523 // FIXME: this comment is cargo culted from the old pass manager, revisit). 524 IP.HintThreshold = 325; 525 526 CGSCCPassManager CGPipeline(DebugLogging); 527 528 CGPipeline.addPass(InlinerPass(IP)); 529 530 FunctionPassManager FPM; 531 FPM.addPass(SROA()); 532 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies. 533 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks. 534 FPM.addPass(InstCombinePass()); // Combine silly sequences. 535 invokePeepholeEPCallbacks(FPM, Level); 536 537 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 538 539 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline))); 540 } 541 542 // Delete anything that is now dead to make sure that we don't instrument 543 // dead code. Instrumentation can end up keeping dead code around and 544 // dramatically increase code size. 545 MPM.addPass(GlobalDCEPass()); 546 547 if (RunProfileGen) { 548 MPM.addPass(PGOInstrumentationGen()); 549 550 FunctionPassManager FPM; 551 FPM.addPass( 552 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging)); 553 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 554 555 // Add the profile lowering pass. 556 InstrProfOptions Options; 557 if (!ProfileGenFile.empty()) 558 Options.InstrProfileOutput = ProfileGenFile; 559 Options.DoCounterPromotion = true; 560 MPM.addPass(InstrProfiling(Options)); 561 } 562 563 if (!ProfileUseFile.empty()) 564 MPM.addPass(PGOInstrumentationUse(ProfileUseFile, ProfileRemappingFile)); 565 } 566 567 static InlineParams 568 getInlineParamsFromOptLevel(PassBuilder::OptimizationLevel Level) { 569 auto O3 = PassBuilder::O3; 570 unsigned OptLevel = Level > O3 ? 2 : Level; 571 unsigned SizeLevel = Level > O3 ? Level - O3 : 0; 572 return getInlineParams(OptLevel, SizeLevel); 573 } 574 575 ModulePassManager 576 PassBuilder::buildModuleSimplificationPipeline(OptimizationLevel Level, 577 ThinLTOPhase Phase, 578 bool DebugLogging) { 579 ModulePassManager MPM(DebugLogging); 580 581 // Do basic inference of function attributes from known properties of system 582 // libraries and other oracles. 583 MPM.addPass(InferFunctionAttrsPass()); 584 585 // Create an early function pass manager to cleanup the output of the 586 // frontend. 587 FunctionPassManager EarlyFPM(DebugLogging); 588 EarlyFPM.addPass(SimplifyCFGPass()); 589 EarlyFPM.addPass(SROA()); 590 EarlyFPM.addPass(EarlyCSEPass()); 591 EarlyFPM.addPass(LowerExpectIntrinsicPass()); 592 if (Level == O3) 593 EarlyFPM.addPass(CallSiteSplittingPass()); 594 595 // In SamplePGO ThinLTO backend, we need instcombine before profile annotation 596 // to convert bitcast to direct calls so that they can be inlined during the 597 // profile annotation prepration step. 598 // More details about SamplePGO design can be found in: 599 // https://research.google.com/pubs/pub45290.html 600 // FIXME: revisit how SampleProfileLoad/Inliner/ICP is structured. 601 if (PGOOpt && !PGOOpt->SampleProfileFile.empty() && 602 Phase == ThinLTOPhase::PostLink) 603 EarlyFPM.addPass(InstCombinePass()); 604 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 605 606 if (PGOOpt && !PGOOpt->SampleProfileFile.empty()) { 607 // Annotate sample profile right after early FPM to ensure freshness of 608 // the debug info. 609 MPM.addPass(SampleProfileLoaderPass(PGOOpt->SampleProfileFile, 610 PGOOpt->ProfileRemappingFile, 611 Phase == ThinLTOPhase::PreLink)); 612 // Do not invoke ICP in the ThinLTOPrelink phase as it makes it hard 613 // for the profile annotation to be accurate in the ThinLTO backend. 614 if (Phase != ThinLTOPhase::PreLink) 615 // We perform early indirect call promotion here, before globalopt. 616 // This is important for the ThinLTO backend phase because otherwise 617 // imported available_externally functions look unreferenced and are 618 // removed. 619 MPM.addPass(PGOIndirectCallPromotion(Phase == ThinLTOPhase::PostLink, 620 true)); 621 } 622 623 // Interprocedural constant propagation now that basic cleanup has occurred 624 // and prior to optimizing globals. 625 // FIXME: This position in the pipeline hasn't been carefully considered in 626 // years, it should be re-analyzed. 627 MPM.addPass(IPSCCPPass()); 628 629 // Attach metadata to indirect call sites indicating the set of functions 630 // they may target at run-time. This should follow IPSCCP. 631 MPM.addPass(CalledValuePropagationPass()); 632 633 // Optimize globals to try and fold them into constants. 634 MPM.addPass(GlobalOptPass()); 635 636 // Promote any localized globals to SSA registers. 637 // FIXME: Should this instead by a run of SROA? 638 // FIXME: We should probably run instcombine and simplify-cfg afterward to 639 // delete control flows that are dead once globals have been folded to 640 // constants. 641 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 642 643 // Remove any dead arguments exposed by cleanups and constand folding 644 // globals. 645 MPM.addPass(DeadArgumentEliminationPass()); 646 647 // Create a small function pass pipeline to cleanup after all the global 648 // optimizations. 649 FunctionPassManager GlobalCleanupPM(DebugLogging); 650 GlobalCleanupPM.addPass(InstCombinePass()); 651 invokePeepholeEPCallbacks(GlobalCleanupPM, Level); 652 653 GlobalCleanupPM.addPass(SimplifyCFGPass()); 654 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM))); 655 656 // Add all the requested passes for instrumentation PGO, if requested. 657 if (PGOOpt && Phase != ThinLTOPhase::PostLink && 658 (!PGOOpt->ProfileGenFile.empty() || !PGOOpt->ProfileUseFile.empty())) { 659 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen, 660 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile, 661 PGOOpt->ProfileRemappingFile); 662 MPM.addPass(PGOIndirectCallPromotion(false, false)); 663 } 664 665 // Synthesize function entry counts for non-PGO compilation. 666 if (EnableSyntheticCounts && !PGOOpt) 667 MPM.addPass(SyntheticCountsPropagation()); 668 669 // Require the GlobalsAA analysis for the module so we can query it within 670 // the CGSCC pipeline. 671 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 672 673 // Require the ProfileSummaryAnalysis for the module so we can query it within 674 // the inliner pass. 675 MPM.addPass(RequireAnalysisPass<ProfileSummaryAnalysis, Module>()); 676 677 // Now begin the main postorder CGSCC pipeline. 678 // FIXME: The current CGSCC pipeline has its origins in the legacy pass 679 // manager and trying to emulate its precise behavior. Much of this doesn't 680 // make a lot of sense and we should revisit the core CGSCC structure. 681 CGSCCPassManager MainCGPipeline(DebugLogging); 682 683 // Note: historically, the PruneEH pass was run first to deduce nounwind and 684 // generally clean up exception handling overhead. It isn't clear this is 685 // valuable as the inliner doesn't currently care whether it is inlining an 686 // invoke or a call. 687 688 // Run the inliner first. The theory is that we are walking bottom-up and so 689 // the callees have already been fully optimized, and we want to inline them 690 // into the callers so that our optimizations can reflect that. 691 // For PreLinkThinLTO pass, we disable hot-caller heuristic for sample PGO 692 // because it makes profile annotation in the backend inaccurate. 693 InlineParams IP = getInlineParamsFromOptLevel(Level); 694 if (Phase == ThinLTOPhase::PreLink && 695 PGOOpt && !PGOOpt->SampleProfileFile.empty()) 696 IP.HotCallSiteThreshold = 0; 697 MainCGPipeline.addPass(InlinerPass(IP)); 698 699 // Now deduce any function attributes based in the current code. 700 MainCGPipeline.addPass(PostOrderFunctionAttrsPass()); 701 702 // When at O3 add argument promotion to the pass pipeline. 703 // FIXME: It isn't at all clear why this should be limited to O3. 704 if (Level == O3) 705 MainCGPipeline.addPass(ArgumentPromotionPass()); 706 707 // Lastly, add the core function simplification pipeline nested inside the 708 // CGSCC walk. 709 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 710 buildFunctionSimplificationPipeline(Level, Phase, DebugLogging))); 711 712 // We only want to do hot cold splitting once for ThinLTO, during the 713 // post-link ThinLTO. 714 if (EnableHotColdSplit && Phase != ThinLTOPhase::PreLink) 715 MPM.addPass(HotColdSplittingPass()); 716 717 for (auto &C : CGSCCOptimizerLateEPCallbacks) 718 C(MainCGPipeline, Level); 719 720 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try 721 // to detect when we devirtualize indirect calls and iterate the SCC passes 722 // in that case to try and catch knock-on inlining or function attrs 723 // opportunities. Then we add it to the module pipeline by walking the SCCs 724 // in postorder (or bottom-up). 725 MPM.addPass( 726 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass( 727 std::move(MainCGPipeline), MaxDevirtIterations))); 728 729 return MPM; 730 } 731 732 ModulePassManager 733 PassBuilder::buildModuleOptimizationPipeline(OptimizationLevel Level, 734 bool DebugLogging) { 735 ModulePassManager MPM(DebugLogging); 736 737 // Optimize globals now that the module is fully simplified. 738 MPM.addPass(GlobalOptPass()); 739 MPM.addPass(GlobalDCEPass()); 740 741 // Run partial inlining pass to partially inline functions that have 742 // large bodies. 743 if (RunPartialInlining) 744 MPM.addPass(PartialInlinerPass()); 745 746 // Remove avail extern fns and globals definitions since we aren't compiling 747 // an object file for later LTO. For LTO we want to preserve these so they 748 // are eligible for inlining at link-time. Note if they are unreferenced they 749 // will be removed by GlobalDCE later, so this only impacts referenced 750 // available externally globals. Eventually they will be suppressed during 751 // codegen, but eliminating here enables more opportunity for GlobalDCE as it 752 // may make globals referenced by available external functions dead and saves 753 // running remaining passes on the eliminated functions. 754 MPM.addPass(EliminateAvailableExternallyPass()); 755 756 // Do RPO function attribute inference across the module to forward-propagate 757 // attributes where applicable. 758 // FIXME: Is this really an optimization rather than a canonicalization? 759 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 760 761 // Re-require GloblasAA here prior to function passes. This is particularly 762 // useful as the above will have inlined, DCE'ed, and function-attr 763 // propagated everything. We should at this point have a reasonably minimal 764 // and richly annotated call graph. By computing aliasing and mod/ref 765 // information for all local globals here, the late loop passes and notably 766 // the vectorizer will be able to use them to help recognize vectorizable 767 // memory operations. 768 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 769 770 FunctionPassManager OptimizePM(DebugLogging); 771 OptimizePM.addPass(Float2IntPass()); 772 // FIXME: We need to run some loop optimizations to re-rotate loops after 773 // simplify-cfg and others undo their rotation. 774 775 // Optimize the loop execution. These passes operate on entire loop nests 776 // rather than on each loop in an inside-out manner, and so they are actually 777 // function passes. 778 779 for (auto &C : VectorizerStartEPCallbacks) 780 C(OptimizePM, Level); 781 782 // First rotate loops that may have been un-rotated by prior passes. 783 OptimizePM.addPass( 784 createFunctionToLoopPassAdaptor(LoopRotatePass(), DebugLogging)); 785 786 // Distribute loops to allow partial vectorization. I.e. isolate dependences 787 // into separate loop that would otherwise inhibit vectorization. This is 788 // currently only performed for loops marked with the metadata 789 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 790 OptimizePM.addPass(LoopDistributePass()); 791 792 // Now run the core loop vectorizer. 793 OptimizePM.addPass(LoopVectorizePass()); 794 795 // Eliminate loads by forwarding stores from the previous iteration to loads 796 // of the current iteration. 797 OptimizePM.addPass(LoopLoadEliminationPass()); 798 799 // Cleanup after the loop optimization passes. 800 OptimizePM.addPass(InstCombinePass()); 801 802 // Now that we've formed fast to execute loop structures, we do further 803 // optimizations. These are run afterward as they might block doing complex 804 // analyses and transforms such as what are needed for loop vectorization. 805 806 // Cleanup after loop vectorization, etc. Simplification passes like CVP and 807 // GVN, loop transforms, and others have already run, so it's now better to 808 // convert to more optimized IR using more aggressive simplify CFG options. 809 // The extra sinking transform can create larger basic blocks, so do this 810 // before SLP vectorization. 811 OptimizePM.addPass(SimplifyCFGPass(SimplifyCFGOptions(). 812 forwardSwitchCondToPhi(true). 813 convertSwitchToLookupTable(true). 814 needCanonicalLoops(false). 815 sinkCommonInsts(true))); 816 817 // Optimize parallel scalar instruction chains into SIMD instructions. 818 OptimizePM.addPass(SLPVectorizerPass()); 819 820 OptimizePM.addPass(InstCombinePass()); 821 822 // Unroll small loops to hide loop backedge latency and saturate any parallel 823 // execution resources of an out-of-order processor. We also then need to 824 // clean up redundancies and loop invariant code. 825 // FIXME: It would be really good to use a loop-integrated instruction 826 // combiner for cleanup here so that the unrolling and LICM can be pipelined 827 // across the loop nests. 828 // We do UnrollAndJam in a separate LPM to ensure it happens before unroll 829 if (EnableUnrollAndJam) { 830 OptimizePM.addPass( 831 createFunctionToLoopPassAdaptor(LoopUnrollAndJamPass(Level))); 832 } 833 OptimizePM.addPass(LoopUnrollPass(Level)); 834 OptimizePM.addPass(InstCombinePass()); 835 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 836 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass(), DebugLogging)); 837 838 // Now that we've vectorized and unrolled loops, we may have more refined 839 // alignment information, try to re-derive it here. 840 OptimizePM.addPass(AlignmentFromAssumptionsPass()); 841 842 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 843 // canonicalization pass that enables other optimizations. As a result, 844 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 845 // result too early. 846 OptimizePM.addPass(LoopSinkPass()); 847 848 // And finally clean up LCSSA form before generating code. 849 OptimizePM.addPass(InstSimplifyPass()); 850 851 // This hoists/decomposes div/rem ops. It should run after other sink/hoist 852 // passes to avoid re-sinking, but before SimplifyCFG because it can allow 853 // flattening of blocks. 854 OptimizePM.addPass(DivRemPairsPass()); 855 856 // LoopSink (and other loop passes since the last simplifyCFG) might have 857 // resulted in single-entry-single-exit or empty blocks. Clean up the CFG. 858 OptimizePM.addPass(SimplifyCFGPass()); 859 860 // Optimize PHIs by speculating around them when profitable. Note that this 861 // pass needs to be run after any PRE or similar pass as it is essentially 862 // inserting redudnancies into the progrem. This even includes SimplifyCFG. 863 OptimizePM.addPass(SpeculateAroundPHIsPass()); 864 865 // Add the core optimizing pipeline. 866 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM))); 867 868 MPM.addPass(CGProfilePass()); 869 870 // Now we need to do some global optimization transforms. 871 // FIXME: It would seem like these should come first in the optimization 872 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird 873 // ordering here. 874 MPM.addPass(GlobalDCEPass()); 875 MPM.addPass(ConstantMergePass()); 876 877 return MPM; 878 } 879 880 ModulePassManager 881 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level, 882 bool DebugLogging) { 883 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 884 885 ModulePassManager MPM(DebugLogging); 886 887 // Force any function attributes we want the rest of the pipeline to observe. 888 MPM.addPass(ForceFunctionAttrsPass()); 889 890 // Apply module pipeline start EP callback. 891 for (auto &C : PipelineStartEPCallbacks) 892 C(MPM); 893 894 if (PGOOpt && PGOOpt->SamplePGOSupport) 895 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 896 897 // Add the core simplification pipeline. 898 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::None, 899 DebugLogging)); 900 901 // Now add the optimization pipeline. 902 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging)); 903 904 return MPM; 905 } 906 907 ModulePassManager 908 PassBuilder::buildThinLTOPreLinkDefaultPipeline(OptimizationLevel Level, 909 bool DebugLogging) { 910 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 911 912 ModulePassManager MPM(DebugLogging); 913 914 // Force any function attributes we want the rest of the pipeline to observe. 915 MPM.addPass(ForceFunctionAttrsPass()); 916 917 if (PGOOpt && PGOOpt->SamplePGOSupport) 918 MPM.addPass(createModuleToFunctionPassAdaptor(AddDiscriminatorsPass())); 919 920 // Apply module pipeline start EP callback. 921 for (auto &C : PipelineStartEPCallbacks) 922 C(MPM); 923 924 // If we are planning to perform ThinLTO later, we don't bloat the code with 925 // unrolling/vectorization/... now. Just simplify the module as much as we 926 // can. 927 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PreLink, 928 DebugLogging)); 929 930 // Run partial inlining pass to partially inline functions that have 931 // large bodies. 932 // FIXME: It isn't clear whether this is really the right place to run this 933 // in ThinLTO. Because there is another canonicalization and simplification 934 // phase that will run after the thin link, running this here ends up with 935 // less information than will be available later and it may grow functions in 936 // ways that aren't beneficial. 937 if (RunPartialInlining) 938 MPM.addPass(PartialInlinerPass()); 939 940 // Reduce the size of the IR as much as possible. 941 MPM.addPass(GlobalOptPass()); 942 943 return MPM; 944 } 945 946 ModulePassManager PassBuilder::buildThinLTODefaultPipeline( 947 OptimizationLevel Level, bool DebugLogging, 948 const ModuleSummaryIndex *ImportSummary) { 949 ModulePassManager MPM(DebugLogging); 950 951 if (ImportSummary) { 952 // These passes import type identifier resolutions for whole-program 953 // devirtualization and CFI. They must run early because other passes may 954 // disturb the specific instruction patterns that these passes look for, 955 // creating dependencies on resolutions that may not appear in the summary. 956 // 957 // For example, GVN may transform the pattern assume(type.test) appearing in 958 // two basic blocks into assume(phi(type.test, type.test)), which would 959 // transform a dependency on a WPD resolution into a dependency on a type 960 // identifier resolution for CFI. 961 // 962 // Also, WPD has access to more precise information than ICP and can 963 // devirtualize more effectively, so it should operate on the IR first. 964 MPM.addPass(WholeProgramDevirtPass(nullptr, ImportSummary)); 965 MPM.addPass(LowerTypeTestsPass(nullptr, ImportSummary)); 966 } 967 968 // Force any function attributes we want the rest of the pipeline to observe. 969 MPM.addPass(ForceFunctionAttrsPass()); 970 971 // During the ThinLTO backend phase we perform early indirect call promotion 972 // here, before globalopt. Otherwise imported available_externally functions 973 // look unreferenced and are removed. 974 // FIXME: move this into buildModuleSimplificationPipeline to merge the logic 975 // with SamplePGO. 976 if (!PGOOpt || PGOOpt->SampleProfileFile.empty()) 977 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, 978 false /* SamplePGO */)); 979 980 // Add the core simplification pipeline. 981 MPM.addPass(buildModuleSimplificationPipeline(Level, ThinLTOPhase::PostLink, 982 DebugLogging)); 983 984 // Now add the optimization pipeline. 985 MPM.addPass(buildModuleOptimizationPipeline(Level, DebugLogging)); 986 987 return MPM; 988 } 989 990 ModulePassManager 991 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level, 992 bool DebugLogging) { 993 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 994 // FIXME: We should use a customized pre-link pipeline! 995 return buildPerModuleDefaultPipeline(Level, DebugLogging); 996 } 997 998 ModulePassManager 999 PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, bool DebugLogging, 1000 ModuleSummaryIndex *ExportSummary) { 1001 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 1002 ModulePassManager MPM(DebugLogging); 1003 1004 // Remove unused virtual tables to improve the quality of code generated by 1005 // whole-program devirtualization and bitset lowering. 1006 MPM.addPass(GlobalDCEPass()); 1007 1008 // Force any function attributes we want the rest of the pipeline to observe. 1009 MPM.addPass(ForceFunctionAttrsPass()); 1010 1011 // Do basic inference of function attributes from known properties of system 1012 // libraries and other oracles. 1013 MPM.addPass(InferFunctionAttrsPass()); 1014 1015 if (Level > 1) { 1016 FunctionPassManager EarlyFPM(DebugLogging); 1017 EarlyFPM.addPass(CallSiteSplittingPass()); 1018 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 1019 1020 // Indirect call promotion. This should promote all the targets that are 1021 // left by the earlier promotion pass that promotes intra-module targets. 1022 // This two-step promotion is to save the compile time. For LTO, it should 1023 // produce the same result as if we only do promotion here. 1024 MPM.addPass(PGOIndirectCallPromotion( 1025 true /* InLTO */, PGOOpt && !PGOOpt->SampleProfileFile.empty())); 1026 // Propagate constants at call sites into the functions they call. This 1027 // opens opportunities for globalopt (and inlining) by substituting function 1028 // pointers passed as arguments to direct uses of functions. 1029 MPM.addPass(IPSCCPPass()); 1030 1031 // Attach metadata to indirect call sites indicating the set of functions 1032 // they may target at run-time. This should follow IPSCCP. 1033 MPM.addPass(CalledValuePropagationPass()); 1034 } 1035 1036 // Now deduce any function attributes based in the current code. 1037 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1038 PostOrderFunctionAttrsPass())); 1039 1040 // Do RPO function attribute inference across the module to forward-propagate 1041 // attributes where applicable. 1042 // FIXME: Is this really an optimization rather than a canonicalization? 1043 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 1044 1045 // Use inragne annotations on GEP indices to split globals where beneficial. 1046 MPM.addPass(GlobalSplitPass()); 1047 1048 // Run whole program optimization of virtual call when the list of callees 1049 // is fixed. 1050 MPM.addPass(WholeProgramDevirtPass(ExportSummary, nullptr)); 1051 1052 // Stop here at -O1. 1053 if (Level == 1) { 1054 // The LowerTypeTestsPass needs to run to lower type metadata and the 1055 // type.test intrinsics. The pass does nothing if CFI is disabled. 1056 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1057 return MPM; 1058 } 1059 1060 // Optimize globals to try and fold them into constants. 1061 MPM.addPass(GlobalOptPass()); 1062 1063 // Promote any localized globals to SSA registers. 1064 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 1065 1066 // Linking modules together can lead to duplicate global constant, only 1067 // keep one copy of each constant. 1068 MPM.addPass(ConstantMergePass()); 1069 1070 // Remove unused arguments from functions. 1071 MPM.addPass(DeadArgumentEliminationPass()); 1072 1073 // Reduce the code after globalopt and ipsccp. Both can open up significant 1074 // simplification opportunities, and both can propagate functions through 1075 // function pointers. When this happens, we often have to resolve varargs 1076 // calls, etc, so let instcombine do this. 1077 FunctionPassManager PeepholeFPM(DebugLogging); 1078 if (Level == O3) 1079 PeepholeFPM.addPass(AggressiveInstCombinePass()); 1080 PeepholeFPM.addPass(InstCombinePass()); 1081 invokePeepholeEPCallbacks(PeepholeFPM, Level); 1082 1083 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(PeepholeFPM))); 1084 1085 // Note: historically, the PruneEH pass was run first to deduce nounwind and 1086 // generally clean up exception handling overhead. It isn't clear this is 1087 // valuable as the inliner doesn't currently care whether it is inlining an 1088 // invoke or a call. 1089 // Run the inliner now. 1090 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1091 InlinerPass(getInlineParamsFromOptLevel(Level)))); 1092 1093 // Optimize globals again after we ran the inliner. 1094 MPM.addPass(GlobalOptPass()); 1095 1096 // Garbage collect dead functions. 1097 // FIXME: Add ArgumentPromotion pass after once it's ported. 1098 MPM.addPass(GlobalDCEPass()); 1099 1100 FunctionPassManager FPM(DebugLogging); 1101 // The IPO Passes may leave cruft around. Clean up after them. 1102 FPM.addPass(InstCombinePass()); 1103 invokePeepholeEPCallbacks(FPM, Level); 1104 1105 FPM.addPass(JumpThreadingPass()); 1106 1107 // Break up allocas 1108 FPM.addPass(SROA()); 1109 1110 // Run a few AA driver optimizations here and now to cleanup the code. 1111 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1112 1113 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 1114 PostOrderFunctionAttrsPass())); 1115 // FIXME: here we run IP alias analysis in the legacy PM. 1116 1117 FunctionPassManager MainFPM; 1118 1119 // FIXME: once we fix LoopPass Manager, add LICM here. 1120 // FIXME: once we provide support for enabling MLSM, add it here. 1121 // FIXME: once we provide support for enabling NewGVN, add it here. 1122 if (RunNewGVN) 1123 MainFPM.addPass(NewGVNPass()); 1124 else 1125 MainFPM.addPass(GVN()); 1126 1127 // Remove dead memcpy()'s. 1128 MainFPM.addPass(MemCpyOptPass()); 1129 1130 // Nuke dead stores. 1131 MainFPM.addPass(DSEPass()); 1132 1133 // FIXME: at this point, we run a bunch of loop passes: 1134 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool, 1135 // loopVectorize. Enable them once the remaining issue with LPM 1136 // are sorted out. 1137 1138 MainFPM.addPass(InstCombinePass()); 1139 MainFPM.addPass(SimplifyCFGPass()); 1140 MainFPM.addPass(SCCPPass()); 1141 MainFPM.addPass(InstCombinePass()); 1142 MainFPM.addPass(BDCEPass()); 1143 1144 // FIXME: We may want to run SLPVectorizer here. 1145 // After vectorization, assume intrinsics may tell us more 1146 // about pointer alignments. 1147 #if 0 1148 MainFPM.add(AlignmentFromAssumptionsPass()); 1149 #endif 1150 1151 // FIXME: Conditionally run LoadCombine here, after it's ported 1152 // (in case we still have this pass, given its questionable usefulness). 1153 1154 MainFPM.addPass(InstCombinePass()); 1155 invokePeepholeEPCallbacks(MainFPM, Level); 1156 MainFPM.addPass(JumpThreadingPass()); 1157 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM))); 1158 1159 // Create a function that performs CFI checks for cross-DSO calls with 1160 // targets in the current module. 1161 MPM.addPass(CrossDSOCFIPass()); 1162 1163 // Lower type metadata and the type.test intrinsic. This pass supports 1164 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs 1165 // to be run at link time if CFI is enabled. This pass does nothing if 1166 // CFI is disabled. 1167 MPM.addPass(LowerTypeTestsPass(ExportSummary, nullptr)); 1168 1169 // Add late LTO optimization passes. 1170 // Delete basic blocks, which optimization passes may have killed. 1171 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass())); 1172 1173 // Drop bodies of available eternally objects to improve GlobalDCE. 1174 MPM.addPass(EliminateAvailableExternallyPass()); 1175 1176 // Now that we have optimized the program, discard unreachable functions. 1177 MPM.addPass(GlobalDCEPass()); 1178 1179 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe. 1180 return MPM; 1181 } 1182 1183 AAManager PassBuilder::buildDefaultAAPipeline() { 1184 AAManager AA; 1185 1186 // The order in which these are registered determines their priority when 1187 // being queried. 1188 1189 // First we register the basic alias analysis that provides the majority of 1190 // per-function local AA logic. This is a stateless, on-demand local set of 1191 // AA techniques. 1192 AA.registerFunctionAnalysis<BasicAA>(); 1193 1194 // Next we query fast, specialized alias analyses that wrap IR-embedded 1195 // information about aliasing. 1196 AA.registerFunctionAnalysis<ScopedNoAliasAA>(); 1197 AA.registerFunctionAnalysis<TypeBasedAA>(); 1198 1199 // Add support for querying global aliasing information when available. 1200 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module 1201 // analysis, all that the `AAManager` can do is query for any *cached* 1202 // results from `GlobalsAA` through a readonly proxy. 1203 AA.registerModuleAnalysis<GlobalsAA>(); 1204 1205 return AA; 1206 } 1207 1208 static Optional<int> parseRepeatPassName(StringRef Name) { 1209 if (!Name.consume_front("repeat<") || !Name.consume_back(">")) 1210 return None; 1211 int Count; 1212 if (Name.getAsInteger(0, Count) || Count <= 0) 1213 return None; 1214 return Count; 1215 } 1216 1217 static Optional<int> parseDevirtPassName(StringRef Name) { 1218 if (!Name.consume_front("devirt<") || !Name.consume_back(">")) 1219 return None; 1220 int Count; 1221 if (Name.getAsInteger(0, Count) || Count <= 0) 1222 return None; 1223 return Count; 1224 } 1225 1226 /// Tests whether a pass name starts with a valid prefix for a default pipeline 1227 /// alias. 1228 static bool startsWithDefaultPipelineAliasPrefix(StringRef Name) { 1229 return Name.startswith("default") || Name.startswith("thinlto") || 1230 Name.startswith("lto"); 1231 } 1232 1233 /// Tests whether registered callbacks will accept a given pass name. 1234 /// 1235 /// When parsing a pipeline text, the type of the outermost pipeline may be 1236 /// omitted, in which case the type is automatically determined from the first 1237 /// pass name in the text. This may be a name that is handled through one of the 1238 /// callbacks. We check this through the oridinary parsing callbacks by setting 1239 /// up a dummy PassManager in order to not force the client to also handle this 1240 /// type of query. 1241 template <typename PassManagerT, typename CallbacksT> 1242 static bool callbacksAcceptPassName(StringRef Name, CallbacksT &Callbacks) { 1243 if (!Callbacks.empty()) { 1244 PassManagerT DummyPM; 1245 for (auto &CB : Callbacks) 1246 if (CB(Name, DummyPM, {})) 1247 return true; 1248 } 1249 return false; 1250 } 1251 1252 template <typename CallbacksT> 1253 static bool isModulePassName(StringRef Name, CallbacksT &Callbacks) { 1254 // Manually handle aliases for pre-configured pipeline fragments. 1255 if (startsWithDefaultPipelineAliasPrefix(Name)) 1256 return DefaultAliasRegex.match(Name); 1257 1258 // Explicitly handle pass manager names. 1259 if (Name == "module") 1260 return true; 1261 if (Name == "cgscc") 1262 return true; 1263 if (Name == "function") 1264 return true; 1265 1266 // Explicitly handle custom-parsed pass names. 1267 if (parseRepeatPassName(Name)) 1268 return true; 1269 1270 #define MODULE_PASS(NAME, CREATE_PASS) \ 1271 if (Name == NAME) \ 1272 return true; 1273 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 1274 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1275 return true; 1276 #include "PassRegistry.def" 1277 1278 return callbacksAcceptPassName<ModulePassManager>(Name, Callbacks); 1279 } 1280 1281 template <typename CallbacksT> 1282 static bool isCGSCCPassName(StringRef Name, CallbacksT &Callbacks) { 1283 // Explicitly handle pass manager names. 1284 if (Name == "cgscc") 1285 return true; 1286 if (Name == "function") 1287 return true; 1288 1289 // Explicitly handle custom-parsed pass names. 1290 if (parseRepeatPassName(Name)) 1291 return true; 1292 if (parseDevirtPassName(Name)) 1293 return true; 1294 1295 #define CGSCC_PASS(NAME, CREATE_PASS) \ 1296 if (Name == NAME) \ 1297 return true; 1298 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 1299 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1300 return true; 1301 #include "PassRegistry.def" 1302 1303 return callbacksAcceptPassName<CGSCCPassManager>(Name, Callbacks); 1304 } 1305 1306 template <typename CallbacksT> 1307 static bool isFunctionPassName(StringRef Name, CallbacksT &Callbacks) { 1308 // Explicitly handle pass manager names. 1309 if (Name == "function") 1310 return true; 1311 if (Name == "loop") 1312 return true; 1313 1314 // Explicitly handle custom-parsed pass names. 1315 if (parseRepeatPassName(Name)) 1316 return true; 1317 1318 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 1319 if (Name == NAME) \ 1320 return true; 1321 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 1322 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1323 return true; 1324 #include "PassRegistry.def" 1325 1326 return callbacksAcceptPassName<FunctionPassManager>(Name, Callbacks); 1327 } 1328 1329 template <typename CallbacksT> 1330 static bool isLoopPassName(StringRef Name, CallbacksT &Callbacks) { 1331 // Explicitly handle pass manager names. 1332 if (Name == "loop") 1333 return true; 1334 1335 // Explicitly handle custom-parsed pass names. 1336 if (parseRepeatPassName(Name)) 1337 return true; 1338 1339 #define LOOP_PASS(NAME, CREATE_PASS) \ 1340 if (Name == NAME) \ 1341 return true; 1342 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 1343 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 1344 return true; 1345 #include "PassRegistry.def" 1346 1347 return callbacksAcceptPassName<LoopPassManager>(Name, Callbacks); 1348 } 1349 1350 Optional<std::vector<PassBuilder::PipelineElement>> 1351 PassBuilder::parsePipelineText(StringRef Text) { 1352 std::vector<PipelineElement> ResultPipeline; 1353 1354 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = { 1355 &ResultPipeline}; 1356 for (;;) { 1357 std::vector<PipelineElement> &Pipeline = *PipelineStack.back(); 1358 size_t Pos = Text.find_first_of(",()"); 1359 Pipeline.push_back({Text.substr(0, Pos), {}}); 1360 1361 // If we have a single terminating name, we're done. 1362 if (Pos == Text.npos) 1363 break; 1364 1365 char Sep = Text[Pos]; 1366 Text = Text.substr(Pos + 1); 1367 if (Sep == ',') 1368 // Just a name ending in a comma, continue. 1369 continue; 1370 1371 if (Sep == '(') { 1372 // Push the inner pipeline onto the stack to continue processing. 1373 PipelineStack.push_back(&Pipeline.back().InnerPipeline); 1374 continue; 1375 } 1376 1377 assert(Sep == ')' && "Bogus separator!"); 1378 // When handling the close parenthesis, we greedily consume them to avoid 1379 // empty strings in the pipeline. 1380 do { 1381 // If we try to pop the outer pipeline we have unbalanced parentheses. 1382 if (PipelineStack.size() == 1) 1383 return None; 1384 1385 PipelineStack.pop_back(); 1386 } while (Text.consume_front(")")); 1387 1388 // Check if we've finished parsing. 1389 if (Text.empty()) 1390 break; 1391 1392 // Otherwise, the end of an inner pipeline always has to be followed by 1393 // a comma, and then we can continue. 1394 if (!Text.consume_front(",")) 1395 return None; 1396 } 1397 1398 if (PipelineStack.size() > 1) 1399 // Unbalanced paretheses. 1400 return None; 1401 1402 assert(PipelineStack.back() == &ResultPipeline && 1403 "Wrong pipeline at the bottom of the stack!"); 1404 return {std::move(ResultPipeline)}; 1405 } 1406 1407 Error PassBuilder::parseModulePass(ModulePassManager &MPM, 1408 const PipelineElement &E, 1409 bool VerifyEachPass, bool DebugLogging) { 1410 auto &Name = E.Name; 1411 auto &InnerPipeline = E.InnerPipeline; 1412 1413 // First handle complex passes like the pass managers which carry pipelines. 1414 if (!InnerPipeline.empty()) { 1415 if (Name == "module") { 1416 ModulePassManager NestedMPM(DebugLogging); 1417 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline, 1418 VerifyEachPass, DebugLogging)) 1419 return Err; 1420 MPM.addPass(std::move(NestedMPM)); 1421 return Error::success(); 1422 } 1423 if (Name == "cgscc") { 1424 CGSCCPassManager CGPM(DebugLogging); 1425 if (auto Err = parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass, 1426 DebugLogging)) 1427 return Err; 1428 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM))); 1429 return Error::success(); 1430 } 1431 if (Name == "function") { 1432 FunctionPassManager FPM(DebugLogging); 1433 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline, 1434 VerifyEachPass, DebugLogging)) 1435 return Err; 1436 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1437 return Error::success(); 1438 } 1439 if (auto Count = parseRepeatPassName(Name)) { 1440 ModulePassManager NestedMPM(DebugLogging); 1441 if (auto Err = parseModulePassPipeline(NestedMPM, InnerPipeline, 1442 VerifyEachPass, DebugLogging)) 1443 return Err; 1444 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM))); 1445 return Error::success(); 1446 } 1447 1448 for (auto &C : ModulePipelineParsingCallbacks) 1449 if (C(Name, MPM, InnerPipeline)) 1450 return Error::success(); 1451 1452 // Normal passes can't have pipelines. 1453 return make_error<StringError>( 1454 formatv("invalid use of '{0}' pass as module pipeline", Name).str(), 1455 inconvertibleErrorCode()); 1456 ; 1457 } 1458 1459 // Manually handle aliases for pre-configured pipeline fragments. 1460 if (startsWithDefaultPipelineAliasPrefix(Name)) { 1461 SmallVector<StringRef, 3> Matches; 1462 if (!DefaultAliasRegex.match(Name, &Matches)) 1463 return make_error<StringError>( 1464 formatv("unknown default pipeline alias '{0}'", Name).str(), 1465 inconvertibleErrorCode()); 1466 1467 assert(Matches.size() == 3 && "Must capture two matched strings!"); 1468 1469 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2]) 1470 .Case("O0", O0) 1471 .Case("O1", O1) 1472 .Case("O2", O2) 1473 .Case("O3", O3) 1474 .Case("Os", Os) 1475 .Case("Oz", Oz); 1476 if (L == O0) 1477 // At O0 we do nothing at all! 1478 return Error::success(); 1479 1480 if (Matches[1] == "default") { 1481 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging)); 1482 } else if (Matches[1] == "thinlto-pre-link") { 1483 MPM.addPass(buildThinLTOPreLinkDefaultPipeline(L, DebugLogging)); 1484 } else if (Matches[1] == "thinlto") { 1485 MPM.addPass(buildThinLTODefaultPipeline(L, DebugLogging, nullptr)); 1486 } else if (Matches[1] == "lto-pre-link") { 1487 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging)); 1488 } else { 1489 assert(Matches[1] == "lto" && "Not one of the matched options!"); 1490 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging, nullptr)); 1491 } 1492 return Error::success(); 1493 } 1494 1495 // Finally expand the basic registered passes from the .inc file. 1496 #define MODULE_PASS(NAME, CREATE_PASS) \ 1497 if (Name == NAME) { \ 1498 MPM.addPass(CREATE_PASS); \ 1499 return Error::success(); \ 1500 } 1501 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 1502 if (Name == "require<" NAME ">") { \ 1503 MPM.addPass( \ 1504 RequireAnalysisPass< \ 1505 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \ 1506 return Error::success(); \ 1507 } \ 1508 if (Name == "invalidate<" NAME ">") { \ 1509 MPM.addPass(InvalidateAnalysisPass< \ 1510 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1511 return Error::success(); \ 1512 } 1513 #include "PassRegistry.def" 1514 1515 for (auto &C : ModulePipelineParsingCallbacks) 1516 if (C(Name, MPM, InnerPipeline)) 1517 return Error::success(); 1518 return make_error<StringError>( 1519 formatv("unknown module pass '{0}'", Name).str(), 1520 inconvertibleErrorCode()); 1521 } 1522 1523 Error PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM, 1524 const PipelineElement &E, bool VerifyEachPass, 1525 bool DebugLogging) { 1526 auto &Name = E.Name; 1527 auto &InnerPipeline = E.InnerPipeline; 1528 1529 // First handle complex passes like the pass managers which carry pipelines. 1530 if (!InnerPipeline.empty()) { 1531 if (Name == "cgscc") { 1532 CGSCCPassManager NestedCGPM(DebugLogging); 1533 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 1534 VerifyEachPass, DebugLogging)) 1535 return Err; 1536 // Add the nested pass manager with the appropriate adaptor. 1537 CGPM.addPass(std::move(NestedCGPM)); 1538 return Error::success(); 1539 } 1540 if (Name == "function") { 1541 FunctionPassManager FPM(DebugLogging); 1542 if (auto Err = parseFunctionPassPipeline(FPM, InnerPipeline, 1543 VerifyEachPass, DebugLogging)) 1544 return Err; 1545 // Add the nested pass manager with the appropriate adaptor. 1546 CGPM.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 1547 return Error::success(); 1548 } 1549 if (auto Count = parseRepeatPassName(Name)) { 1550 CGSCCPassManager NestedCGPM(DebugLogging); 1551 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 1552 VerifyEachPass, DebugLogging)) 1553 return Err; 1554 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM))); 1555 return Error::success(); 1556 } 1557 if (auto MaxRepetitions = parseDevirtPassName(Name)) { 1558 CGSCCPassManager NestedCGPM(DebugLogging); 1559 if (auto Err = parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, 1560 VerifyEachPass, DebugLogging)) 1561 return Err; 1562 CGPM.addPass( 1563 createDevirtSCCRepeatedPass(std::move(NestedCGPM), *MaxRepetitions)); 1564 return Error::success(); 1565 } 1566 1567 for (auto &C : CGSCCPipelineParsingCallbacks) 1568 if (C(Name, CGPM, InnerPipeline)) 1569 return Error::success(); 1570 1571 // Normal passes can't have pipelines. 1572 return make_error<StringError>( 1573 formatv("invalid use of '{0}' pass as cgscc pipeline", Name).str(), 1574 inconvertibleErrorCode()); 1575 } 1576 1577 // Now expand the basic registered passes from the .inc file. 1578 #define CGSCC_PASS(NAME, CREATE_PASS) \ 1579 if (Name == NAME) { \ 1580 CGPM.addPass(CREATE_PASS); \ 1581 return Error::success(); \ 1582 } 1583 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 1584 if (Name == "require<" NAME ">") { \ 1585 CGPM.addPass(RequireAnalysisPass< \ 1586 std::remove_reference<decltype(CREATE_PASS)>::type, \ 1587 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \ 1588 CGSCCUpdateResult &>()); \ 1589 return Error::success(); \ 1590 } \ 1591 if (Name == "invalidate<" NAME ">") { \ 1592 CGPM.addPass(InvalidateAnalysisPass< \ 1593 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1594 return Error::success(); \ 1595 } 1596 #include "PassRegistry.def" 1597 1598 for (auto &C : CGSCCPipelineParsingCallbacks) 1599 if (C(Name, CGPM, InnerPipeline)) 1600 return Error::success(); 1601 return make_error<StringError>( 1602 formatv("unknown cgscc pass '{0}'", Name).str(), 1603 inconvertibleErrorCode()); 1604 } 1605 1606 Error PassBuilder::parseFunctionPass(FunctionPassManager &FPM, 1607 const PipelineElement &E, 1608 bool VerifyEachPass, bool DebugLogging) { 1609 auto &Name = E.Name; 1610 auto &InnerPipeline = E.InnerPipeline; 1611 1612 // First handle complex passes like the pass managers which carry pipelines. 1613 if (!InnerPipeline.empty()) { 1614 if (Name == "function") { 1615 FunctionPassManager NestedFPM(DebugLogging); 1616 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline, 1617 VerifyEachPass, DebugLogging)) 1618 return Err; 1619 // Add the nested pass manager with the appropriate adaptor. 1620 FPM.addPass(std::move(NestedFPM)); 1621 return Error::success(); 1622 } 1623 if (Name == "loop") { 1624 LoopPassManager LPM(DebugLogging); 1625 if (auto Err = parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass, 1626 DebugLogging)) 1627 return Err; 1628 // Add the nested pass manager with the appropriate adaptor. 1629 FPM.addPass( 1630 createFunctionToLoopPassAdaptor(std::move(LPM), DebugLogging)); 1631 return Error::success(); 1632 } 1633 if (auto Count = parseRepeatPassName(Name)) { 1634 FunctionPassManager NestedFPM(DebugLogging); 1635 if (auto Err = parseFunctionPassPipeline(NestedFPM, InnerPipeline, 1636 VerifyEachPass, DebugLogging)) 1637 return Err; 1638 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM))); 1639 return Error::success(); 1640 } 1641 1642 for (auto &C : FunctionPipelineParsingCallbacks) 1643 if (C(Name, FPM, InnerPipeline)) 1644 return Error::success(); 1645 1646 // Normal passes can't have pipelines. 1647 return make_error<StringError>( 1648 formatv("invalid use of '{0}' pass as function pipeline", Name).str(), 1649 inconvertibleErrorCode()); 1650 } 1651 1652 // Now expand the basic registered passes from the .inc file. 1653 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 1654 if (Name == NAME) { \ 1655 FPM.addPass(CREATE_PASS); \ 1656 return Error::success(); \ 1657 } 1658 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 1659 if (Name == "require<" NAME ">") { \ 1660 FPM.addPass( \ 1661 RequireAnalysisPass< \ 1662 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \ 1663 return Error::success(); \ 1664 } \ 1665 if (Name == "invalidate<" NAME ">") { \ 1666 FPM.addPass(InvalidateAnalysisPass< \ 1667 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1668 return Error::success(); \ 1669 } 1670 #include "PassRegistry.def" 1671 1672 for (auto &C : FunctionPipelineParsingCallbacks) 1673 if (C(Name, FPM, InnerPipeline)) 1674 return Error::success(); 1675 return make_error<StringError>( 1676 formatv("unknown function pass '{0}'", Name).str(), 1677 inconvertibleErrorCode()); 1678 } 1679 1680 Error PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E, 1681 bool VerifyEachPass, bool DebugLogging) { 1682 StringRef Name = E.Name; 1683 auto &InnerPipeline = E.InnerPipeline; 1684 1685 // First handle complex passes like the pass managers which carry pipelines. 1686 if (!InnerPipeline.empty()) { 1687 if (Name == "loop") { 1688 LoopPassManager NestedLPM(DebugLogging); 1689 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline, 1690 VerifyEachPass, DebugLogging)) 1691 return Err; 1692 // Add the nested pass manager with the appropriate adaptor. 1693 LPM.addPass(std::move(NestedLPM)); 1694 return Error::success(); 1695 } 1696 if (auto Count = parseRepeatPassName(Name)) { 1697 LoopPassManager NestedLPM(DebugLogging); 1698 if (auto Err = parseLoopPassPipeline(NestedLPM, InnerPipeline, 1699 VerifyEachPass, DebugLogging)) 1700 return Err; 1701 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM))); 1702 return Error::success(); 1703 } 1704 1705 for (auto &C : LoopPipelineParsingCallbacks) 1706 if (C(Name, LPM, InnerPipeline)) 1707 return Error::success(); 1708 1709 // Normal passes can't have pipelines. 1710 return make_error<StringError>( 1711 formatv("invalid use of '{0}' pass as loop pipeline", Name).str(), 1712 inconvertibleErrorCode()); 1713 } 1714 1715 // Now expand the basic registered passes from the .inc file. 1716 #define LOOP_PASS(NAME, CREATE_PASS) \ 1717 if (Name == NAME) { \ 1718 LPM.addPass(CREATE_PASS); \ 1719 return Error::success(); \ 1720 } 1721 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 1722 if (Name == "require<" NAME ">") { \ 1723 LPM.addPass(RequireAnalysisPass< \ 1724 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \ 1725 LoopAnalysisManager, LoopStandardAnalysisResults &, \ 1726 LPMUpdater &>()); \ 1727 return Error::success(); \ 1728 } \ 1729 if (Name == "invalidate<" NAME ">") { \ 1730 LPM.addPass(InvalidateAnalysisPass< \ 1731 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1732 return Error::success(); \ 1733 } 1734 #include "PassRegistry.def" 1735 1736 for (auto &C : LoopPipelineParsingCallbacks) 1737 if (C(Name, LPM, InnerPipeline)) 1738 return Error::success(); 1739 return make_error<StringError>(formatv("unknown loop pass '{0}'", Name).str(), 1740 inconvertibleErrorCode()); 1741 } 1742 1743 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) { 1744 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 1745 if (Name == NAME) { \ 1746 AA.registerModuleAnalysis< \ 1747 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 1748 return true; \ 1749 } 1750 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 1751 if (Name == NAME) { \ 1752 AA.registerFunctionAnalysis< \ 1753 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 1754 return true; \ 1755 } 1756 #include "PassRegistry.def" 1757 1758 for (auto &C : AAParsingCallbacks) 1759 if (C(Name, AA)) 1760 return true; 1761 return false; 1762 } 1763 1764 Error PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM, 1765 ArrayRef<PipelineElement> Pipeline, 1766 bool VerifyEachPass, 1767 bool DebugLogging) { 1768 for (const auto &Element : Pipeline) { 1769 if (auto Err = parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging)) 1770 return Err; 1771 // FIXME: No verifier support for Loop passes! 1772 } 1773 return Error::success(); 1774 } 1775 1776 Error PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM, 1777 ArrayRef<PipelineElement> Pipeline, 1778 bool VerifyEachPass, 1779 bool DebugLogging) { 1780 for (const auto &Element : Pipeline) { 1781 if (auto Err = 1782 parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging)) 1783 return Err; 1784 if (VerifyEachPass) 1785 FPM.addPass(VerifierPass()); 1786 } 1787 return Error::success(); 1788 } 1789 1790 Error PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM, 1791 ArrayRef<PipelineElement> Pipeline, 1792 bool VerifyEachPass, 1793 bool DebugLogging) { 1794 for (const auto &Element : Pipeline) { 1795 if (auto Err = parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging)) 1796 return Err; 1797 // FIXME: No verifier support for CGSCC passes! 1798 } 1799 return Error::success(); 1800 } 1801 1802 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM, 1803 FunctionAnalysisManager &FAM, 1804 CGSCCAnalysisManager &CGAM, 1805 ModuleAnalysisManager &MAM) { 1806 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); }); 1807 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); }); 1808 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); }); 1809 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); }); 1810 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); }); 1811 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); }); 1812 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); }); 1813 } 1814 1815 Error PassBuilder::parseModulePassPipeline(ModulePassManager &MPM, 1816 ArrayRef<PipelineElement> Pipeline, 1817 bool VerifyEachPass, 1818 bool DebugLogging) { 1819 for (const auto &Element : Pipeline) { 1820 if (auto Err = parseModulePass(MPM, Element, VerifyEachPass, DebugLogging)) 1821 return Err; 1822 if (VerifyEachPass) 1823 MPM.addPass(VerifierPass()); 1824 } 1825 return Error::success(); 1826 } 1827 1828 // Primary pass pipeline description parsing routine for a \c ModulePassManager 1829 // FIXME: Should this routine accept a TargetMachine or require the caller to 1830 // pre-populate the analysis managers with target-specific stuff? 1831 Error PassBuilder::parsePassPipeline(ModulePassManager &MPM, 1832 StringRef PipelineText, 1833 bool VerifyEachPass, bool DebugLogging) { 1834 auto Pipeline = parsePipelineText(PipelineText); 1835 if (!Pipeline || Pipeline->empty()) 1836 return make_error<StringError>( 1837 formatv("invalid pipeline '{0}'", PipelineText).str(), 1838 inconvertibleErrorCode()); 1839 1840 // If the first name isn't at the module layer, wrap the pipeline up 1841 // automatically. 1842 StringRef FirstName = Pipeline->front().Name; 1843 1844 if (!isModulePassName(FirstName, ModulePipelineParsingCallbacks)) { 1845 if (isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) { 1846 Pipeline = {{"cgscc", std::move(*Pipeline)}}; 1847 } else if (isFunctionPassName(FirstName, 1848 FunctionPipelineParsingCallbacks)) { 1849 Pipeline = {{"function", std::move(*Pipeline)}}; 1850 } else if (isLoopPassName(FirstName, LoopPipelineParsingCallbacks)) { 1851 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}}; 1852 } else { 1853 for (auto &C : TopLevelPipelineParsingCallbacks) 1854 if (C(MPM, *Pipeline, VerifyEachPass, DebugLogging)) 1855 return Error::success(); 1856 1857 // Unknown pass or pipeline name! 1858 auto &InnerPipeline = Pipeline->front().InnerPipeline; 1859 return make_error<StringError>( 1860 formatv("unknown {0} name '{1}'", 1861 (InnerPipeline.empty() ? "pass" : "pipeline"), FirstName) 1862 .str(), 1863 inconvertibleErrorCode()); 1864 } 1865 } 1866 1867 if (auto Err = 1868 parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging)) 1869 return Err; 1870 return Error::success(); 1871 } 1872 1873 // Primary pass pipeline description parsing routine for a \c CGSCCPassManager 1874 Error PassBuilder::parsePassPipeline(CGSCCPassManager &CGPM, 1875 StringRef PipelineText, 1876 bool VerifyEachPass, bool DebugLogging) { 1877 auto Pipeline = parsePipelineText(PipelineText); 1878 if (!Pipeline || Pipeline->empty()) 1879 return make_error<StringError>( 1880 formatv("invalid pipeline '{0}'", PipelineText).str(), 1881 inconvertibleErrorCode()); 1882 1883 StringRef FirstName = Pipeline->front().Name; 1884 if (!isCGSCCPassName(FirstName, CGSCCPipelineParsingCallbacks)) 1885 return make_error<StringError>( 1886 formatv("unknown cgscc pass '{0}' in pipeline '{1}'", FirstName, 1887 PipelineText) 1888 .str(), 1889 inconvertibleErrorCode()); 1890 1891 if (auto Err = 1892 parseCGSCCPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging)) 1893 return Err; 1894 return Error::success(); 1895 } 1896 1897 // Primary pass pipeline description parsing routine for a \c 1898 // FunctionPassManager 1899 Error PassBuilder::parsePassPipeline(FunctionPassManager &FPM, 1900 StringRef PipelineText, 1901 bool VerifyEachPass, bool DebugLogging) { 1902 auto Pipeline = parsePipelineText(PipelineText); 1903 if (!Pipeline || Pipeline->empty()) 1904 return make_error<StringError>( 1905 formatv("invalid pipeline '{0}'", PipelineText).str(), 1906 inconvertibleErrorCode()); 1907 1908 StringRef FirstName = Pipeline->front().Name; 1909 if (!isFunctionPassName(FirstName, FunctionPipelineParsingCallbacks)) 1910 return make_error<StringError>( 1911 formatv("unknown function pass '{0}' in pipeline '{1}'", FirstName, 1912 PipelineText) 1913 .str(), 1914 inconvertibleErrorCode()); 1915 1916 if (auto Err = parseFunctionPassPipeline(FPM, *Pipeline, VerifyEachPass, 1917 DebugLogging)) 1918 return Err; 1919 return Error::success(); 1920 } 1921 1922 // Primary pass pipeline description parsing routine for a \c LoopPassManager 1923 Error PassBuilder::parsePassPipeline(LoopPassManager &CGPM, 1924 StringRef PipelineText, 1925 bool VerifyEachPass, bool DebugLogging) { 1926 auto Pipeline = parsePipelineText(PipelineText); 1927 if (!Pipeline || Pipeline->empty()) 1928 return make_error<StringError>( 1929 formatv("invalid pipeline '{0}'", PipelineText).str(), 1930 inconvertibleErrorCode()); 1931 1932 if (auto Err = 1933 parseLoopPassPipeline(CGPM, *Pipeline, VerifyEachPass, DebugLogging)) 1934 return Err; 1935 1936 return Error::success(); 1937 } 1938 1939 Error PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) { 1940 // If the pipeline just consists of the word 'default' just replace the AA 1941 // manager with our default one. 1942 if (PipelineText == "default") { 1943 AA = buildDefaultAAPipeline(); 1944 return Error::success(); 1945 } 1946 1947 while (!PipelineText.empty()) { 1948 StringRef Name; 1949 std::tie(Name, PipelineText) = PipelineText.split(','); 1950 if (!parseAAPassName(AA, Name)) 1951 return make_error<StringError>( 1952 formatv("unknown alias analysis name '{0}'", Name).str(), 1953 inconvertibleErrorCode()); 1954 } 1955 1956 return Error::success(); 1957 } 1958