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/BlockFrequencyInfoImpl.h" 26 #include "llvm/Analysis/BranchProbabilityInfo.h" 27 #include "llvm/Analysis/CFGPrinter.h" 28 #include "llvm/Analysis/CFLAndersAliasAnalysis.h" 29 #include "llvm/Analysis/CFLSteensAliasAnalysis.h" 30 #include "llvm/Analysis/CGSCCPassManager.h" 31 #include "llvm/Analysis/CallGraph.h" 32 #include "llvm/Analysis/DemandedBits.h" 33 #include "llvm/Analysis/DependenceAnalysis.h" 34 #include "llvm/Analysis/DominanceFrontier.h" 35 #include "llvm/Analysis/GlobalsModRef.h" 36 #include "llvm/Analysis/IVUsers.h" 37 #include "llvm/Analysis/LazyCallGraph.h" 38 #include "llvm/Analysis/LazyValueInfo.h" 39 #include "llvm/Analysis/LoopAccessAnalysis.h" 40 #include "llvm/Analysis/LoopInfo.h" 41 #include "llvm/Analysis/MemoryDependenceAnalysis.h" 42 #include "llvm/Analysis/ModuleSummaryAnalysis.h" 43 #include "llvm/Analysis/OptimizationDiagnosticInfo.h" 44 #include "llvm/Analysis/PostDominators.h" 45 #include "llvm/Analysis/ProfileSummaryInfo.h" 46 #include "llvm/Analysis/RegionInfo.h" 47 #include "llvm/Analysis/ScalarEvolution.h" 48 #include "llvm/Analysis/ScalarEvolutionAliasAnalysis.h" 49 #include "llvm/Analysis/ScopedNoAliasAA.h" 50 #include "llvm/Analysis/TargetLibraryInfo.h" 51 #include "llvm/Analysis/TargetTransformInfo.h" 52 #include "llvm/Analysis/TypeBasedAliasAnalysis.h" 53 #include "llvm/CodeGen/PreISelIntrinsicLowering.h" 54 #include "llvm/CodeGen/UnreachableBlockElim.h" 55 #include "llvm/IR/Dominators.h" 56 #include "llvm/IR/IRPrintingPasses.h" 57 #include "llvm/IR/PassManager.h" 58 #include "llvm/IR/Verifier.h" 59 #include "llvm/Support/Debug.h" 60 #include "llvm/Support/Regex.h" 61 #include "llvm/Target/TargetMachine.h" 62 #include "llvm/Transforms/GCOVProfiler.h" 63 #include "llvm/Transforms/IPO/AlwaysInliner.h" 64 #include "llvm/Transforms/IPO/ArgumentPromotion.h" 65 #include "llvm/Transforms/IPO/ConstantMerge.h" 66 #include "llvm/Transforms/IPO/CrossDSOCFI.h" 67 #include "llvm/Transforms/IPO/DeadArgumentElimination.h" 68 #include "llvm/Transforms/IPO/ElimAvailExtern.h" 69 #include "llvm/Transforms/IPO/ForceFunctionAttrs.h" 70 #include "llvm/Transforms/IPO/FunctionAttrs.h" 71 #include "llvm/Transforms/IPO/FunctionImport.h" 72 #include "llvm/Transforms/IPO/GlobalDCE.h" 73 #include "llvm/Transforms/IPO/GlobalOpt.h" 74 #include "llvm/Transforms/IPO/GlobalSplit.h" 75 #include "llvm/Transforms/IPO/InferFunctionAttrs.h" 76 #include "llvm/Transforms/IPO/Inliner.h" 77 #include "llvm/Transforms/IPO/Internalize.h" 78 #include "llvm/Transforms/IPO/LowerTypeTests.h" 79 #include "llvm/Transforms/IPO/PartialInlining.h" 80 #include "llvm/Transforms/IPO/SCCP.h" 81 #include "llvm/Transforms/IPO/StripDeadPrototypes.h" 82 #include "llvm/Transforms/IPO/WholeProgramDevirt.h" 83 #include "llvm/Transforms/InstCombine/InstCombine.h" 84 #include "llvm/Transforms/InstrProfiling.h" 85 #include "llvm/Transforms/PGOInstrumentation.h" 86 #include "llvm/Transforms/SampleProfile.h" 87 #include "llvm/Transforms/Scalar/ADCE.h" 88 #include "llvm/Transforms/Scalar/AlignmentFromAssumptions.h" 89 #include "llvm/Transforms/Scalar/BDCE.h" 90 #include "llvm/Transforms/Scalar/ConstantHoisting.h" 91 #include "llvm/Transforms/Scalar/CorrelatedValuePropagation.h" 92 #include "llvm/Transforms/Scalar/DCE.h" 93 #include "llvm/Transforms/Scalar/DeadStoreElimination.h" 94 #include "llvm/Transforms/Scalar/EarlyCSE.h" 95 #include "llvm/Transforms/Scalar/Float2Int.h" 96 #include "llvm/Transforms/Scalar/GVN.h" 97 #include "llvm/Transforms/Scalar/GuardWidening.h" 98 #include "llvm/Transforms/Scalar/IVUsersPrinter.h" 99 #include "llvm/Transforms/Scalar/IndVarSimplify.h" 100 #include "llvm/Transforms/Scalar/JumpThreading.h" 101 #include "llvm/Transforms/Scalar/LICM.h" 102 #include "llvm/Transforms/Scalar/LoopAccessAnalysisPrinter.h" 103 #include "llvm/Transforms/Scalar/LoopDataPrefetch.h" 104 #include "llvm/Transforms/Scalar/LoopDeletion.h" 105 #include "llvm/Transforms/Scalar/LoopDistribute.h" 106 #include "llvm/Transforms/Scalar/LoopIdiomRecognize.h" 107 #include "llvm/Transforms/Scalar/LoopInstSimplify.h" 108 #include "llvm/Transforms/Scalar/LoopLoadElimination.h" 109 #include "llvm/Transforms/Scalar/LoopPassManager.h" 110 #include "llvm/Transforms/Scalar/LoopPredication.h" 111 #include "llvm/Transforms/Scalar/LoopRotation.h" 112 #include "llvm/Transforms/Scalar/LoopSimplifyCFG.h" 113 #include "llvm/Transforms/Scalar/LoopSink.h" 114 #include "llvm/Transforms/Scalar/LoopStrengthReduce.h" 115 #include "llvm/Transforms/Scalar/LoopUnrollPass.h" 116 #include "llvm/Transforms/Scalar/LowerAtomic.h" 117 #include "llvm/Transforms/Scalar/LowerExpectIntrinsic.h" 118 #include "llvm/Transforms/Scalar/LowerGuardIntrinsic.h" 119 #include "llvm/Transforms/Scalar/MemCpyOptimizer.h" 120 #include "llvm/Transforms/Scalar/MergedLoadStoreMotion.h" 121 #include "llvm/Transforms/Scalar/NaryReassociate.h" 122 #include "llvm/Transforms/Scalar/NewGVN.h" 123 #include "llvm/Transforms/Scalar/PartiallyInlineLibCalls.h" 124 #include "llvm/Transforms/Scalar/Reassociate.h" 125 #include "llvm/Transforms/Scalar/SCCP.h" 126 #include "llvm/Transforms/Scalar/SROA.h" 127 #include "llvm/Transforms/Scalar/SimplifyCFG.h" 128 #include "llvm/Transforms/Scalar/Sink.h" 129 #include "llvm/Transforms/Scalar/SpeculativeExecution.h" 130 #include "llvm/Transforms/Scalar/TailRecursionElimination.h" 131 #include "llvm/Transforms/Utils/AddDiscriminators.h" 132 #include "llvm/Transforms/Utils/BreakCriticalEdges.h" 133 #include "llvm/Transforms/Utils/LCSSA.h" 134 #include "llvm/Transforms/Utils/LibCallsShrinkWrap.h" 135 #include "llvm/Transforms/Utils/LoopSimplify.h" 136 #include "llvm/Transforms/Utils/LowerInvoke.h" 137 #include "llvm/Transforms/Utils/Mem2Reg.h" 138 #include "llvm/Transforms/Utils/MemorySSA.h" 139 #include "llvm/Transforms/Utils/NameAnonGlobals.h" 140 #include "llvm/Transforms/Utils/PredicateInfo.h" 141 #include "llvm/Transforms/Utils/SimplifyInstructions.h" 142 #include "llvm/Transforms/Utils/SymbolRewriter.h" 143 #include "llvm/Transforms/Vectorize/LoopVectorize.h" 144 #include "llvm/Transforms/Vectorize/SLPVectorizer.h" 145 146 #include <type_traits> 147 148 using namespace llvm; 149 150 static cl::opt<unsigned> MaxDevirtIterations("pm-max-devirt-iterations", 151 cl::ReallyHidden, cl::init(4)); 152 153 static Regex DefaultAliasRegex("^(default|lto-pre-link|lto)<(O[0123sz])>$"); 154 155 static bool isOptimizingForSize(PassBuilder::OptimizationLevel Level) { 156 switch (Level) { 157 case PassBuilder::O0: 158 case PassBuilder::O1: 159 case PassBuilder::O2: 160 case PassBuilder::O3: 161 return false; 162 163 case PassBuilder::Os: 164 case PassBuilder::Oz: 165 return true; 166 } 167 llvm_unreachable("Invalid optimization level!"); 168 } 169 170 namespace { 171 172 /// \brief No-op module pass which does nothing. 173 struct NoOpModulePass { 174 PreservedAnalyses run(Module &M, ModuleAnalysisManager &) { 175 return PreservedAnalyses::all(); 176 } 177 static StringRef name() { return "NoOpModulePass"; } 178 }; 179 180 /// \brief No-op module analysis. 181 class NoOpModuleAnalysis : public AnalysisInfoMixin<NoOpModuleAnalysis> { 182 friend AnalysisInfoMixin<NoOpModuleAnalysis>; 183 static AnalysisKey Key; 184 185 public: 186 struct Result {}; 187 Result run(Module &, ModuleAnalysisManager &) { return Result(); } 188 static StringRef name() { return "NoOpModuleAnalysis"; } 189 }; 190 191 /// \brief No-op CGSCC pass which does nothing. 192 struct NoOpCGSCCPass { 193 PreservedAnalyses run(LazyCallGraph::SCC &C, CGSCCAnalysisManager &, 194 LazyCallGraph &, CGSCCUpdateResult &UR) { 195 return PreservedAnalyses::all(); 196 } 197 static StringRef name() { return "NoOpCGSCCPass"; } 198 }; 199 200 /// \brief No-op CGSCC analysis. 201 class NoOpCGSCCAnalysis : public AnalysisInfoMixin<NoOpCGSCCAnalysis> { 202 friend AnalysisInfoMixin<NoOpCGSCCAnalysis>; 203 static AnalysisKey Key; 204 205 public: 206 struct Result {}; 207 Result run(LazyCallGraph::SCC &, CGSCCAnalysisManager &, LazyCallGraph &G) { 208 return Result(); 209 } 210 static StringRef name() { return "NoOpCGSCCAnalysis"; } 211 }; 212 213 /// \brief No-op function pass which does nothing. 214 struct NoOpFunctionPass { 215 PreservedAnalyses run(Function &F, FunctionAnalysisManager &) { 216 return PreservedAnalyses::all(); 217 } 218 static StringRef name() { return "NoOpFunctionPass"; } 219 }; 220 221 /// \brief No-op function analysis. 222 class NoOpFunctionAnalysis : public AnalysisInfoMixin<NoOpFunctionAnalysis> { 223 friend AnalysisInfoMixin<NoOpFunctionAnalysis>; 224 static AnalysisKey Key; 225 226 public: 227 struct Result {}; 228 Result run(Function &, FunctionAnalysisManager &) { return Result(); } 229 static StringRef name() { return "NoOpFunctionAnalysis"; } 230 }; 231 232 /// \brief No-op loop pass which does nothing. 233 struct NoOpLoopPass { 234 PreservedAnalyses run(Loop &L, LoopAnalysisManager &, 235 LoopStandardAnalysisResults &, LPMUpdater &) { 236 return PreservedAnalyses::all(); 237 } 238 static StringRef name() { return "NoOpLoopPass"; } 239 }; 240 241 /// \brief No-op loop analysis. 242 class NoOpLoopAnalysis : public AnalysisInfoMixin<NoOpLoopAnalysis> { 243 friend AnalysisInfoMixin<NoOpLoopAnalysis>; 244 static AnalysisKey Key; 245 246 public: 247 struct Result {}; 248 Result run(Loop &, LoopAnalysisManager &, LoopStandardAnalysisResults &) { 249 return Result(); 250 } 251 static StringRef name() { return "NoOpLoopAnalysis"; } 252 }; 253 254 AnalysisKey NoOpModuleAnalysis::Key; 255 AnalysisKey NoOpCGSCCAnalysis::Key; 256 AnalysisKey NoOpFunctionAnalysis::Key; 257 AnalysisKey NoOpLoopAnalysis::Key; 258 259 } // End anonymous namespace. 260 261 void PassBuilder::registerModuleAnalyses(ModuleAnalysisManager &MAM) { 262 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 263 MAM.registerPass([&] { return CREATE_PASS; }); 264 #include "PassRegistry.def" 265 } 266 267 void PassBuilder::registerCGSCCAnalyses(CGSCCAnalysisManager &CGAM) { 268 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 269 CGAM.registerPass([&] { return CREATE_PASS; }); 270 #include "PassRegistry.def" 271 } 272 273 void PassBuilder::registerFunctionAnalyses(FunctionAnalysisManager &FAM) { 274 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 275 FAM.registerPass([&] { return CREATE_PASS; }); 276 #include "PassRegistry.def" 277 } 278 279 void PassBuilder::registerLoopAnalyses(LoopAnalysisManager &LAM) { 280 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 281 LAM.registerPass([&] { return CREATE_PASS; }); 282 #include "PassRegistry.def" 283 } 284 285 FunctionPassManager 286 PassBuilder::buildFunctionSimplificationPipeline(OptimizationLevel Level, 287 bool DebugLogging) { 288 assert(Level != O0 && "Must request optimizations!"); 289 FunctionPassManager FPM(DebugLogging); 290 291 // Form SSA out of local memory accesses after breaking apart aggregates into 292 // scalars. 293 FPM.addPass(SROA()); 294 295 // Catch trivial redundancies 296 FPM.addPass(EarlyCSEPass()); 297 298 // Speculative execution if the target has divergent branches; otherwise nop. 299 FPM.addPass(SpeculativeExecutionPass()); 300 301 // Optimize based on known information about branches, and cleanup afterward. 302 FPM.addPass(JumpThreadingPass()); 303 FPM.addPass(CorrelatedValuePropagationPass()); 304 FPM.addPass(SimplifyCFGPass()); 305 FPM.addPass(InstCombinePass()); 306 307 if (!isOptimizingForSize(Level)) 308 FPM.addPass(LibCallsShrinkWrapPass()); 309 310 FPM.addPass(TailCallElimPass()); 311 FPM.addPass(SimplifyCFGPass()); 312 313 // Form canonically associated expression trees, and simplify the trees using 314 // basic mathematical properties. For example, this will form (nearly) 315 // minimal multiplication trees. 316 FPM.addPass(ReassociatePass()); 317 318 // Add the primary loop simplification pipeline. 319 // FIXME: Currently this is split into two loop pass pipelines because we run 320 // some function passes in between them. These can and should be replaced by 321 // loop pass equivalenst but those aren't ready yet. Specifically, 322 // `SimplifyCFGPass` and `InstCombinePass` are used. We have 323 // `LoopSimplifyCFGPass` which isn't yet powerful enough, and the closest to 324 // the other we have is `LoopInstSimplify`. 325 LoopPassManager LPM1(DebugLogging), LPM2(DebugLogging); 326 327 // Rotate Loop - disable header duplication at -Oz 328 LPM1.addPass(LoopRotatePass(Level != Oz)); 329 LPM1.addPass(LICMPass()); 330 #if 0 331 // The LoopUnswitch pass isn't yet ported to the new pass manager. 332 LPM1.addPass(LoopUnswitchPass(/* OptimizeForSize */ Level != O3)); 333 #endif 334 LPM2.addPass(IndVarSimplifyPass()); 335 LPM2.addPass(LoopIdiomRecognizePass()); 336 LPM2.addPass(LoopDeletionPass()); 337 LPM2.addPass(LoopUnrollPass::createFull(Level)); 338 339 // We provide the opt remark emitter pass for LICM to use. We only need to do 340 // this once as it is immutable. 341 FPM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 342 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM1))); 343 FPM.addPass(SimplifyCFGPass()); 344 FPM.addPass(InstCombinePass()); 345 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM2))); 346 347 // Eliminate redundancies. 348 if (Level != O1) { 349 // These passes add substantial compile time so skip them at O1. 350 FPM.addPass(MergedLoadStoreMotionPass()); 351 FPM.addPass(GVN()); 352 } 353 354 // Specially optimize memory movement as it doesn't look like dataflow in SSA. 355 FPM.addPass(MemCpyOptPass()); 356 357 // Sparse conditional constant propagation. 358 // FIXME: It isn't clear why we do this *after* loop passes rather than 359 // before... 360 FPM.addPass(SCCPPass()); 361 362 // Delete dead bit computations (instcombine runs after to fold away the dead 363 // computations, and then ADCE will run later to exploit any new DCE 364 // opportunities that creates). 365 FPM.addPass(BDCEPass()); 366 367 // Run instcombine after redundancy and dead bit elimination to exploit 368 // opportunities opened up by them. 369 FPM.addPass(InstCombinePass()); 370 371 // Re-consider control flow based optimizations after redundancy elimination, 372 // redo DCE, etc. 373 FPM.addPass(JumpThreadingPass()); 374 FPM.addPass(CorrelatedValuePropagationPass()); 375 FPM.addPass(DSEPass()); 376 FPM.addPass(createFunctionToLoopPassAdaptor(LICMPass())); 377 378 // Finally, do an expensive DCE pass to catch all the dead code exposed by 379 // the simplifications and basic cleanup after all the simplifications. 380 FPM.addPass(ADCEPass()); 381 FPM.addPass(SimplifyCFGPass()); 382 FPM.addPass(InstCombinePass()); 383 384 return FPM; 385 } 386 387 static void addPGOInstrPasses(ModulePassManager &MPM, bool DebugLogging, 388 PassBuilder::OptimizationLevel Level, 389 bool RunProfileGen, std::string ProfileGenFile, 390 std::string ProfileUseFile) { 391 // Generally running simplification passes and the inliner with an high 392 // threshold results in smaller executables, but there may be cases where 393 // the size grows, so let's be conservative here and skip this simplification 394 // at -Os/Oz. 395 if (!isOptimizingForSize(Level)) { 396 InlineParams IP; 397 398 // In the old pass manager, this is a cl::opt. Should still this be one? 399 IP.DefaultThreshold = 75; 400 401 // FIXME: The hint threshold has the same value used by the regular inliner. 402 // This should probably be lowered after performance testing. 403 // FIXME: this comment is cargo culted from the old pass manager, revisit). 404 IP.HintThreshold = 325; 405 406 CGSCCPassManager CGPipeline(DebugLogging); 407 408 CGPipeline.addPass(InlinerPass(IP)); 409 410 FunctionPassManager FPM; 411 FPM.addPass(SROA()); 412 FPM.addPass(EarlyCSEPass()); // Catch trivial redundancies. 413 FPM.addPass(SimplifyCFGPass()); // Merge & remove basic blocks. 414 FPM.addPass(InstCombinePass()); // Combine silly sequences. 415 416 // FIXME: Here the old pass manager inserts peephole extensions. 417 // Add them when they're supported. 418 CGPipeline.addPass(createCGSCCToFunctionPassAdaptor(std::move(FPM))); 419 420 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPipeline))); 421 } 422 423 if (RunProfileGen) { 424 MPM.addPass(PGOInstrumentationGen()); 425 426 // Add the profile lowering pass. 427 InstrProfOptions Options; 428 if (!ProfileGenFile.empty()) 429 Options.InstrProfileOutput = ProfileGenFile; 430 MPM.addPass(InstrProfiling(Options)); 431 } 432 433 if (!ProfileUseFile.empty()) 434 MPM.addPass(PGOInstrumentationUse(ProfileUseFile)); 435 } 436 437 ModulePassManager 438 PassBuilder::buildPerModuleDefaultPipeline(OptimizationLevel Level, 439 bool DebugLogging) { 440 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 441 ModulePassManager MPM(DebugLogging); 442 443 // Force any function attributes we want the rest of the pipeline te observe. 444 MPM.addPass(ForceFunctionAttrsPass()); 445 446 // Do basic inference of function attributes from known properties of system 447 // libraries and other oracles. 448 MPM.addPass(InferFunctionAttrsPass()); 449 450 // Create an early function pass manager to cleanup the output of the 451 // frontend. 452 FunctionPassManager EarlyFPM(DebugLogging); 453 EarlyFPM.addPass(SimplifyCFGPass()); 454 EarlyFPM.addPass(SROA()); 455 EarlyFPM.addPass(EarlyCSEPass()); 456 EarlyFPM.addPass(LowerExpectIntrinsicPass()); 457 EarlyFPM.addPass(GVNHoistPass()); 458 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(EarlyFPM))); 459 460 // Interprocedural constant propagation now that basic cleanup has occured 461 // and prior to optimizing globals. 462 // FIXME: This position in the pipeline hasn't been carefully considered in 463 // years, it should be re-analyzed. 464 MPM.addPass(IPSCCPPass()); 465 466 // Optimize globals to try and fold them into constants. 467 MPM.addPass(GlobalOptPass()); 468 469 // Promote any localized globals to SSA registers. 470 // FIXME: Should this instead by a run of SROA? 471 // FIXME: We should probably run instcombine and simplify-cfg afterward to 472 // delete control flows that are dead once globals have been folded to 473 // constants. 474 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 475 476 // Remove any dead arguments exposed by cleanups and constand folding 477 // globals. 478 MPM.addPass(DeadArgumentEliminationPass()); 479 480 // Create a small function pass pipeline to cleanup after all the global 481 // optimizations. 482 FunctionPassManager GlobalCleanupPM(DebugLogging); 483 GlobalCleanupPM.addPass(InstCombinePass()); 484 GlobalCleanupPM.addPass(SimplifyCFGPass()); 485 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(GlobalCleanupPM))); 486 487 // Add all the requested passes for PGO Instrumentation, if requested. 488 if (PGOOpt) { 489 assert(PGOOpt->RunProfileGen || PGOOpt->SamplePGO || 490 !PGOOpt->ProfileUseFile.empty()); 491 addPGOInstrPasses(MPM, DebugLogging, Level, PGOOpt->RunProfileGen, 492 PGOOpt->ProfileGenFile, PGOOpt->ProfileUseFile); 493 } 494 495 // Indirect call promotion that promotes intra-module targes only. 496 MPM.addPass(PGOIndirectCallPromotion(false, PGOOpt && PGOOpt->SamplePGO)); 497 498 // Require the GlobalsAA analysis for the module so we can query it within 499 // the CGSCC pipeline. 500 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 501 502 // Now begin the main postorder CGSCC pipeline. 503 // FIXME: The current CGSCC pipeline has its origins in the legacy pass 504 // manager and trying to emulate its precise behavior. Much of this doesn't 505 // make a lot of sense and we should revisit the core CGSCC structure. 506 CGSCCPassManager MainCGPipeline(DebugLogging); 507 508 // Note: historically, the PruneEH pass was run first to deduce nounwind and 509 // generally clean up exception handling overhead. It isn't clear this is 510 // valuable as the inliner doesn't currently care whether it is inlining an 511 // invoke or a call. 512 513 // Run the inliner first. The theory is that we are walking bottom-up and so 514 // the callees have already been fully optimized, and we want to inline them 515 // into the callers so that our optimizations can reflect that. 516 // FIXME; Customize the threshold based on optimization level. 517 MainCGPipeline.addPass(InlinerPass()); 518 519 // Now deduce any function attributes based in the current code. 520 MainCGPipeline.addPass(PostOrderFunctionAttrsPass()); 521 522 // When at O3 add argument promotion to the pass pipeline. 523 // FIXME: It isn't at all clear why this should be limited to O3. 524 if (Level == O3) 525 MainCGPipeline.addPass(ArgumentPromotionPass()); 526 527 // Lastly, add the core function simplification pipeline nested inside the 528 // CGSCC walk. 529 MainCGPipeline.addPass(createCGSCCToFunctionPassAdaptor( 530 buildFunctionSimplificationPipeline(Level, DebugLogging))); 531 532 // We wrap the CGSCC pipeline in a devirtualization repeater. This will try 533 // to detect when we devirtualize indirect calls and iterate the SCC passes 534 // in that case to try and catch knock-on inlining or function attrs 535 // opportunities. Then we add it to the module pipeline by walking the SCCs 536 // in postorder (or bottom-up). 537 MPM.addPass( 538 createModuleToPostOrderCGSCCPassAdaptor(createDevirtSCCRepeatedPass( 539 std::move(MainCGPipeline), MaxDevirtIterations, DebugLogging))); 540 541 // This ends the canonicalization and simplification phase of the pipeline. 542 // At this point, we expect to have canonical and simple IR which we begin 543 // *optimizing* for efficient execution going forward. 544 545 // Eliminate externally available functions now that inlining is over -- we 546 // won't emit these anyways. 547 MPM.addPass(EliminateAvailableExternallyPass()); 548 549 // Do RPO function attribute inference across the module to forward-propagate 550 // attributes where applicable. 551 // FIXME: Is this really an optimization rather than a canonicalization? 552 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 553 554 // Re-require GloblasAA here prior to function passes. This is particularly 555 // useful as the above will have inlined, DCE'ed, and function-attr 556 // propagated everything. We should at this point have a reasonably minimal 557 // and richly annotated call graph. By computing aliasing and mod/ref 558 // information for all local globals here, the late loop passes and notably 559 // the vectorizer will be able to use them to help recognize vectorizable 560 // memory operations. 561 MPM.addPass(RequireAnalysisPass<GlobalsAA, Module>()); 562 563 FunctionPassManager OptimizePM(DebugLogging); 564 OptimizePM.addPass(Float2IntPass()); 565 // FIXME: We need to run some loop optimizations to re-rotate loops after 566 // simplify-cfg and others undo their rotation. 567 568 // Optimize the loop execution. These passes operate on entire loop nests 569 // rather than on each loop in an inside-out manner, and so they are actually 570 // function passes. 571 572 // First rotate loops that may have been un-rotated by prior passes. 573 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopRotatePass())); 574 575 // Distribute loops to allow partial vectorization. I.e. isolate dependences 576 // into separate loop that would otherwise inhibit vectorization. This is 577 // currently only performed for loops marked with the metadata 578 // llvm.loop.distribute=true or when -enable-loop-distribute is specified. 579 OptimizePM.addPass(LoopDistributePass()); 580 581 // Now run the core loop vectorizer. 582 OptimizePM.addPass(LoopVectorizePass()); 583 584 // Eliminate loads by forwarding stores from the previous iteration to loads 585 // of the current iteration. 586 OptimizePM.addPass(LoopLoadEliminationPass()); 587 588 // Cleanup after the loop optimization passes. 589 OptimizePM.addPass(InstCombinePass()); 590 591 592 // Now that we've formed fast to execute loop structures, we do further 593 // optimizations. These are run afterward as they might block doing complex 594 // analyses and transforms such as what are needed for loop vectorization. 595 596 // Optimize parallel scalar instruction chains into SIMD instructions. 597 OptimizePM.addPass(SLPVectorizerPass()); 598 599 // Cleanup after all of the vectorizers. 600 OptimizePM.addPass(SimplifyCFGPass()); 601 OptimizePM.addPass(InstCombinePass()); 602 603 // Unroll small loops to hide loop backedge latency and saturate any parallel 604 // execution resources of an out-of-order processor. We also then need to 605 // clean up redundancies and loop invariant code. 606 // FIXME: It would be really good to use a loop-integrated instruction 607 // combiner for cleanup here so that the unrolling and LICM can be pipelined 608 // across the loop nests. 609 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LoopUnrollPass::create(Level))); 610 OptimizePM.addPass(InstCombinePass()); 611 OptimizePM.addPass(RequireAnalysisPass<OptimizationRemarkEmitterAnalysis, Function>()); 612 OptimizePM.addPass(createFunctionToLoopPassAdaptor(LICMPass())); 613 614 // Now that we've vectorized and unrolled loops, we may have more refined 615 // alignment information, try to re-derive it here. 616 OptimizePM.addPass(AlignmentFromAssumptionsPass()); 617 618 // LoopSink pass sinks instructions hoisted by LICM, which serves as a 619 // canonicalization pass that enables other optimizations. As a result, 620 // LoopSink pass needs to be a very late IR pass to avoid undoing LICM 621 // result too early. 622 OptimizePM.addPass(LoopSinkPass()); 623 624 // And finally clean up LCSSA form before generating code. 625 OptimizePM.addPass(InstSimplifierPass()); 626 627 // Add the core optimizing pipeline. 628 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(OptimizePM))); 629 630 // Now we need to do some global optimization transforms. 631 // FIXME: It would seem like these should come first in the optimization 632 // pipeline and maybe be the bottom of the canonicalization pipeline? Weird 633 // ordering here. 634 MPM.addPass(GlobalDCEPass()); 635 MPM.addPass(ConstantMergePass()); 636 637 return MPM; 638 } 639 640 ModulePassManager 641 PassBuilder::buildLTOPreLinkDefaultPipeline(OptimizationLevel Level, 642 bool DebugLogging) { 643 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 644 // FIXME: We should use a customized pre-link pipeline! 645 return buildPerModuleDefaultPipeline(Level, DebugLogging); 646 } 647 648 ModulePassManager PassBuilder::buildLTODefaultPipeline(OptimizationLevel Level, 649 bool DebugLogging) { 650 assert(Level != O0 && "Must request optimizations for the default pipeline!"); 651 ModulePassManager MPM(DebugLogging); 652 653 // Remove unused virtual tables to improve the quality of code generated by 654 // whole-program devirtualization and bitset lowering. 655 MPM.addPass(GlobalDCEPass()); 656 657 // Force any function attributes we want the rest of the pipeline to observe. 658 MPM.addPass(ForceFunctionAttrsPass()); 659 660 // Do basic inference of function attributes from known properties of system 661 // libraries and other oracles. 662 MPM.addPass(InferFunctionAttrsPass()); 663 664 if (Level > 1) { 665 // Indirect call promotion. This should promote all the targets that are 666 // left by the earlier promotion pass that promotes intra-module targets. 667 // This two-step promotion is to save the compile time. For LTO, it should 668 // produce the same result as if we only do promotion here. 669 MPM.addPass(PGOIndirectCallPromotion(true /* InLTO */, 670 PGOOpt && PGOOpt->SamplePGO)); 671 672 // Propagate constants at call sites into the functions they call. This 673 // opens opportunities for globalopt (and inlining) by substituting function 674 // pointers passed as arguments to direct uses of functions. 675 MPM.addPass(IPSCCPPass()); 676 } 677 678 // Now deduce any function attributes based in the current code. 679 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 680 PostOrderFunctionAttrsPass())); 681 682 // Do RPO function attribute inference across the module to forward-propagate 683 // attributes where applicable. 684 // FIXME: Is this really an optimization rather than a canonicalization? 685 MPM.addPass(ReversePostOrderFunctionAttrsPass()); 686 687 // Use inragne annotations on GEP indices to split globals where beneficial. 688 MPM.addPass(GlobalSplitPass()); 689 690 // Run whole program optimization of virtual call when the list of callees 691 // is fixed. 692 MPM.addPass(WholeProgramDevirtPass()); 693 694 // Stop here at -O1. 695 if (Level == 1) 696 return MPM; 697 698 // Optimize globals to try and fold them into constants. 699 MPM.addPass(GlobalOptPass()); 700 701 // Promote any localized globals to SSA registers. 702 MPM.addPass(createModuleToFunctionPassAdaptor(PromotePass())); 703 704 // Linking modules together can lead to duplicate global constant, only 705 // keep one copy of each constant. 706 MPM.addPass(ConstantMergePass()); 707 708 // Remove unused arguments from functions. 709 MPM.addPass(DeadArgumentEliminationPass()); 710 711 // Reduce the code after globalopt and ipsccp. Both can open up significant 712 // simplification opportunities, and both can propagate functions through 713 // function pointers. When this happens, we often have to resolve varargs 714 // calls, etc, so let instcombine do this. 715 // FIXME: add peephole extensions here as the legacy PM does. 716 MPM.addPass(createModuleToFunctionPassAdaptor(InstCombinePass())); 717 718 // Note: historically, the PruneEH pass was run first to deduce nounwind and 719 // generally clean up exception handling overhead. It isn't clear this is 720 // valuable as the inliner doesn't currently care whether it is inlining an 721 // invoke or a call. 722 // Run the inliner now. 723 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(InlinerPass())); 724 725 // Optimize globals again after we ran the inliner. 726 MPM.addPass(GlobalOptPass()); 727 728 // Garbage collect dead functions. 729 // FIXME: Add ArgumentPromotion pass after once it's ported. 730 MPM.addPass(GlobalDCEPass()); 731 732 FunctionPassManager FPM(DebugLogging); 733 734 // The IPO Passes may leave cruft around. Clean up after them. 735 // FIXME: add peephole extensions here as the legacy PM does. 736 FPM.addPass(InstCombinePass()); 737 FPM.addPass(JumpThreadingPass()); 738 739 // Break up allocas 740 FPM.addPass(SROA()); 741 742 // Run a few AA driver optimizations here and now to cleanup the code. 743 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 744 745 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor( 746 PostOrderFunctionAttrsPass())); 747 // FIXME: here we run IP alias analysis in the legacy PM. 748 749 FunctionPassManager MainFPM; 750 751 // FIXME: once we fix LoopPass Manager, add LICM here. 752 // FIXME: once we provide support for enabling MLSM, add it here. 753 // FIXME: once we provide support for enabling NewGVN, add it here. 754 MainFPM.addPass(GVN()); 755 756 // Remove dead memcpy()'s. 757 MainFPM.addPass(MemCpyOptPass()); 758 759 // Nuke dead stores. 760 MainFPM.addPass(DSEPass()); 761 762 // FIXME: at this point, we run a bunch of loop passes: 763 // indVarSimplify, loopDeletion, loopInterchange, loopUnrool, 764 // loopVectorize. Enable them once the remaining issue with LPM 765 // are sorted out. 766 767 MainFPM.addPass(InstCombinePass()); 768 MainFPM.addPass(SimplifyCFGPass()); 769 MainFPM.addPass(SCCPPass()); 770 MainFPM.addPass(InstCombinePass()); 771 MainFPM.addPass(BDCEPass()); 772 773 // FIXME: We may want to run SLPVectorizer here. 774 // After vectorization, assume intrinsics may tell us more 775 // about pointer alignments. 776 #if 0 777 MainFPM.add(AlignmentFromAssumptionsPass()); 778 #endif 779 780 // FIXME: Conditionally run LoadCombine here, after it's ported 781 // (in case we still have this pass, given its questionable usefulness). 782 783 // FIXME: add peephole extensions to the PM here. 784 MainFPM.addPass(InstCombinePass()); 785 MainFPM.addPass(JumpThreadingPass()); 786 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(MainFPM))); 787 788 // Create a function that performs CFI checks for cross-DSO calls with 789 // targets in the current module. 790 MPM.addPass(CrossDSOCFIPass()); 791 792 // Lower type metadata and the type.test intrinsic. This pass supports 793 // clang's control flow integrity mechanisms (-fsanitize=cfi*) and needs 794 // to be run at link time if CFI is enabled. This pass does nothing if 795 // CFI is disabled. 796 // Enable once we add support for the summary in the new PM. 797 #if 0 798 MPM.addPass(LowerTypeTestsPass(Summary ? PassSummaryAction::Export : 799 PassSummaryAction::None, 800 Summary)); 801 #endif 802 803 // Add late LTO optimization passes. 804 // Delete basic blocks, which optimization passes may have killed. 805 MPM.addPass(createModuleToFunctionPassAdaptor(SimplifyCFGPass())); 806 807 // Drop bodies of available eternally objects to improve GlobalDCE. 808 MPM.addPass(EliminateAvailableExternallyPass()); 809 810 // Now that we have optimized the program, discard unreachable functions. 811 MPM.addPass(GlobalDCEPass()); 812 813 // FIXME: Enable MergeFuncs, conditionally, after ported, maybe. 814 return MPM; 815 } 816 817 AAManager PassBuilder::buildDefaultAAPipeline() { 818 AAManager AA; 819 820 // The order in which these are registered determines their priority when 821 // being queried. 822 823 // First we register the basic alias analysis that provides the majority of 824 // per-function local AA logic. This is a stateless, on-demand local set of 825 // AA techniques. 826 AA.registerFunctionAnalysis<BasicAA>(); 827 828 // Next we query fast, specialized alias analyses that wrap IR-embedded 829 // information about aliasing. 830 AA.registerFunctionAnalysis<ScopedNoAliasAA>(); 831 AA.registerFunctionAnalysis<TypeBasedAA>(); 832 833 // Add support for querying global aliasing information when available. 834 // Because the `AAManager` is a function analysis and `GlobalsAA` is a module 835 // analysis, all that the `AAManager` can do is query for any *cached* 836 // results from `GlobalsAA` through a readonly proxy. 837 AA.registerModuleAnalysis<GlobalsAA>(); 838 839 return AA; 840 } 841 842 static Optional<int> parseRepeatPassName(StringRef Name) { 843 if (!Name.consume_front("repeat<") || !Name.consume_back(">")) 844 return None; 845 int Count; 846 if (Name.getAsInteger(0, Count) || Count <= 0) 847 return None; 848 return Count; 849 } 850 851 static Optional<int> parseDevirtPassName(StringRef Name) { 852 if (!Name.consume_front("devirt<") || !Name.consume_back(">")) 853 return None; 854 int Count; 855 if (Name.getAsInteger(0, Count) || Count <= 0) 856 return None; 857 return Count; 858 } 859 860 static bool isModulePassName(StringRef Name) { 861 // Manually handle aliases for pre-configured pipeline fragments. 862 if (Name.startswith("default") || Name.startswith("lto")) 863 return DefaultAliasRegex.match(Name); 864 865 // Explicitly handle pass manager names. 866 if (Name == "module") 867 return true; 868 if (Name == "cgscc") 869 return true; 870 if (Name == "function") 871 return true; 872 873 // Explicitly handle custom-parsed pass names. 874 if (parseRepeatPassName(Name)) 875 return true; 876 877 #define MODULE_PASS(NAME, CREATE_PASS) \ 878 if (Name == NAME) \ 879 return true; 880 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 881 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 882 return true; 883 #include "PassRegistry.def" 884 885 return false; 886 } 887 888 static bool isCGSCCPassName(StringRef Name) { 889 // Explicitly handle pass manager names. 890 if (Name == "cgscc") 891 return true; 892 if (Name == "function") 893 return true; 894 895 // Explicitly handle custom-parsed pass names. 896 if (parseRepeatPassName(Name)) 897 return true; 898 if (parseDevirtPassName(Name)) 899 return true; 900 901 #define CGSCC_PASS(NAME, CREATE_PASS) \ 902 if (Name == NAME) \ 903 return true; 904 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 905 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 906 return true; 907 #include "PassRegistry.def" 908 909 return false; 910 } 911 912 static bool isFunctionPassName(StringRef Name) { 913 // Explicitly handle pass manager names. 914 if (Name == "function") 915 return true; 916 if (Name == "loop") 917 return true; 918 919 // Explicitly handle custom-parsed pass names. 920 if (parseRepeatPassName(Name)) 921 return true; 922 923 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 924 if (Name == NAME) \ 925 return true; 926 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 927 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 928 return true; 929 #include "PassRegistry.def" 930 931 return false; 932 } 933 934 static bool isLoopPassName(StringRef Name) { 935 // Explicitly handle pass manager names. 936 if (Name == "loop") 937 return true; 938 939 // Explicitly handle custom-parsed pass names. 940 if (parseRepeatPassName(Name)) 941 return true; 942 943 #define LOOP_PASS(NAME, CREATE_PASS) \ 944 if (Name == NAME) \ 945 return true; 946 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 947 if (Name == "require<" NAME ">" || Name == "invalidate<" NAME ">") \ 948 return true; 949 #include "PassRegistry.def" 950 951 return false; 952 } 953 954 Optional<std::vector<PassBuilder::PipelineElement>> 955 PassBuilder::parsePipelineText(StringRef Text) { 956 std::vector<PipelineElement> ResultPipeline; 957 958 SmallVector<std::vector<PipelineElement> *, 4> PipelineStack = { 959 &ResultPipeline}; 960 for (;;) { 961 std::vector<PipelineElement> &Pipeline = *PipelineStack.back(); 962 size_t Pos = Text.find_first_of(",()"); 963 Pipeline.push_back({Text.substr(0, Pos), {}}); 964 965 // If we have a single terminating name, we're done. 966 if (Pos == Text.npos) 967 break; 968 969 char Sep = Text[Pos]; 970 Text = Text.substr(Pos + 1); 971 if (Sep == ',') 972 // Just a name ending in a comma, continue. 973 continue; 974 975 if (Sep == '(') { 976 // Push the inner pipeline onto the stack to continue processing. 977 PipelineStack.push_back(&Pipeline.back().InnerPipeline); 978 continue; 979 } 980 981 assert(Sep == ')' && "Bogus separator!"); 982 // When handling the close parenthesis, we greedily consume them to avoid 983 // empty strings in the pipeline. 984 do { 985 // If we try to pop the outer pipeline we have unbalanced parentheses. 986 if (PipelineStack.size() == 1) 987 return None; 988 989 PipelineStack.pop_back(); 990 } while (Text.consume_front(")")); 991 992 // Check if we've finished parsing. 993 if (Text.empty()) 994 break; 995 996 // Otherwise, the end of an inner pipeline always has to be followed by 997 // a comma, and then we can continue. 998 if (!Text.consume_front(",")) 999 return None; 1000 } 1001 1002 if (PipelineStack.size() > 1) 1003 // Unbalanced paretheses. 1004 return None; 1005 1006 assert(PipelineStack.back() == &ResultPipeline && 1007 "Wrong pipeline at the bottom of the stack!"); 1008 return {std::move(ResultPipeline)}; 1009 } 1010 1011 bool PassBuilder::parseModulePass(ModulePassManager &MPM, 1012 const PipelineElement &E, bool VerifyEachPass, 1013 bool DebugLogging) { 1014 auto &Name = E.Name; 1015 auto &InnerPipeline = E.InnerPipeline; 1016 1017 // First handle complex passes like the pass managers which carry pipelines. 1018 if (!InnerPipeline.empty()) { 1019 if (Name == "module") { 1020 ModulePassManager NestedMPM(DebugLogging); 1021 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass, 1022 DebugLogging)) 1023 return false; 1024 MPM.addPass(std::move(NestedMPM)); 1025 return true; 1026 } 1027 if (Name == "cgscc") { 1028 CGSCCPassManager CGPM(DebugLogging); 1029 if (!parseCGSCCPassPipeline(CGPM, InnerPipeline, VerifyEachPass, 1030 DebugLogging)) 1031 return false; 1032 MPM.addPass(createModuleToPostOrderCGSCCPassAdaptor(std::move(CGPM), 1033 DebugLogging)); 1034 return true; 1035 } 1036 if (Name == "function") { 1037 FunctionPassManager FPM(DebugLogging); 1038 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass, 1039 DebugLogging)) 1040 return false; 1041 MPM.addPass(createModuleToFunctionPassAdaptor(std::move(FPM))); 1042 return true; 1043 } 1044 if (auto Count = parseRepeatPassName(Name)) { 1045 ModulePassManager NestedMPM(DebugLogging); 1046 if (!parseModulePassPipeline(NestedMPM, InnerPipeline, VerifyEachPass, 1047 DebugLogging)) 1048 return false; 1049 MPM.addPass(createRepeatedPass(*Count, std::move(NestedMPM))); 1050 return true; 1051 } 1052 // Normal passes can't have pipelines. 1053 return false; 1054 } 1055 1056 // Manually handle aliases for pre-configured pipeline fragments. 1057 if (Name.startswith("default") || Name.startswith("lto")) { 1058 SmallVector<StringRef, 3> Matches; 1059 if (!DefaultAliasRegex.match(Name, &Matches)) 1060 return false; 1061 assert(Matches.size() == 3 && "Must capture two matched strings!"); 1062 1063 OptimizationLevel L = StringSwitch<OptimizationLevel>(Matches[2]) 1064 .Case("O0", O0) 1065 .Case("O1", O1) 1066 .Case("O2", O2) 1067 .Case("O3", O3) 1068 .Case("Os", Os) 1069 .Case("Oz", Oz); 1070 if (L == O0) 1071 // At O0 we do nothing at all! 1072 return true; 1073 1074 if (Matches[1] == "default") { 1075 MPM.addPass(buildPerModuleDefaultPipeline(L, DebugLogging)); 1076 } else if (Matches[1] == "lto-pre-link") { 1077 MPM.addPass(buildLTOPreLinkDefaultPipeline(L, DebugLogging)); 1078 } else { 1079 assert(Matches[1] == "lto" && "Not one of the matched options!"); 1080 MPM.addPass(buildLTODefaultPipeline(L, DebugLogging)); 1081 } 1082 return true; 1083 } 1084 1085 // Finally expand the basic registered passes from the .inc file. 1086 #define MODULE_PASS(NAME, CREATE_PASS) \ 1087 if (Name == NAME) { \ 1088 MPM.addPass(CREATE_PASS); \ 1089 return true; \ 1090 } 1091 #define MODULE_ANALYSIS(NAME, CREATE_PASS) \ 1092 if (Name == "require<" NAME ">") { \ 1093 MPM.addPass( \ 1094 RequireAnalysisPass< \ 1095 std::remove_reference<decltype(CREATE_PASS)>::type, Module>()); \ 1096 return true; \ 1097 } \ 1098 if (Name == "invalidate<" NAME ">") { \ 1099 MPM.addPass(InvalidateAnalysisPass< \ 1100 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1101 return true; \ 1102 } 1103 #include "PassRegistry.def" 1104 1105 return false; 1106 } 1107 1108 bool PassBuilder::parseCGSCCPass(CGSCCPassManager &CGPM, 1109 const PipelineElement &E, bool VerifyEachPass, 1110 bool DebugLogging) { 1111 auto &Name = E.Name; 1112 auto &InnerPipeline = E.InnerPipeline; 1113 1114 // First handle complex passes like the pass managers which carry pipelines. 1115 if (!InnerPipeline.empty()) { 1116 if (Name == "cgscc") { 1117 CGSCCPassManager NestedCGPM(DebugLogging); 1118 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass, 1119 DebugLogging)) 1120 return false; 1121 // Add the nested pass manager with the appropriate adaptor. 1122 CGPM.addPass(std::move(NestedCGPM)); 1123 return true; 1124 } 1125 if (Name == "function") { 1126 FunctionPassManager FPM(DebugLogging); 1127 if (!parseFunctionPassPipeline(FPM, InnerPipeline, VerifyEachPass, 1128 DebugLogging)) 1129 return false; 1130 // Add the nested pass manager with the appropriate adaptor. 1131 CGPM.addPass( 1132 createCGSCCToFunctionPassAdaptor(std::move(FPM), DebugLogging)); 1133 return true; 1134 } 1135 if (auto Count = parseRepeatPassName(Name)) { 1136 CGSCCPassManager NestedCGPM(DebugLogging); 1137 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass, 1138 DebugLogging)) 1139 return false; 1140 CGPM.addPass(createRepeatedPass(*Count, std::move(NestedCGPM))); 1141 return true; 1142 } 1143 if (auto MaxRepetitions = parseDevirtPassName(Name)) { 1144 CGSCCPassManager NestedCGPM(DebugLogging); 1145 if (!parseCGSCCPassPipeline(NestedCGPM, InnerPipeline, VerifyEachPass, 1146 DebugLogging)) 1147 return false; 1148 CGPM.addPass(createDevirtSCCRepeatedPass(std::move(NestedCGPM), 1149 *MaxRepetitions, DebugLogging)); 1150 return true; 1151 } 1152 // Normal passes can't have pipelines. 1153 return false; 1154 } 1155 1156 // Now expand the basic registered passes from the .inc file. 1157 #define CGSCC_PASS(NAME, CREATE_PASS) \ 1158 if (Name == NAME) { \ 1159 CGPM.addPass(CREATE_PASS); \ 1160 return true; \ 1161 } 1162 #define CGSCC_ANALYSIS(NAME, CREATE_PASS) \ 1163 if (Name == "require<" NAME ">") { \ 1164 CGPM.addPass(RequireAnalysisPass< \ 1165 std::remove_reference<decltype(CREATE_PASS)>::type, \ 1166 LazyCallGraph::SCC, CGSCCAnalysisManager, LazyCallGraph &, \ 1167 CGSCCUpdateResult &>()); \ 1168 return true; \ 1169 } \ 1170 if (Name == "invalidate<" NAME ">") { \ 1171 CGPM.addPass(InvalidateAnalysisPass< \ 1172 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1173 return true; \ 1174 } 1175 #include "PassRegistry.def" 1176 1177 return false; 1178 } 1179 1180 bool PassBuilder::parseFunctionPass(FunctionPassManager &FPM, 1181 const PipelineElement &E, 1182 bool VerifyEachPass, bool DebugLogging) { 1183 auto &Name = E.Name; 1184 auto &InnerPipeline = E.InnerPipeline; 1185 1186 // First handle complex passes like the pass managers which carry pipelines. 1187 if (!InnerPipeline.empty()) { 1188 if (Name == "function") { 1189 FunctionPassManager NestedFPM(DebugLogging); 1190 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass, 1191 DebugLogging)) 1192 return false; 1193 // Add the nested pass manager with the appropriate adaptor. 1194 FPM.addPass(std::move(NestedFPM)); 1195 return true; 1196 } 1197 if (Name == "loop") { 1198 LoopPassManager LPM(DebugLogging); 1199 if (!parseLoopPassPipeline(LPM, InnerPipeline, VerifyEachPass, 1200 DebugLogging)) 1201 return false; 1202 // Add the nested pass manager with the appropriate adaptor. 1203 FPM.addPass(createFunctionToLoopPassAdaptor(std::move(LPM))); 1204 return true; 1205 } 1206 if (auto Count = parseRepeatPassName(Name)) { 1207 FunctionPassManager NestedFPM(DebugLogging); 1208 if (!parseFunctionPassPipeline(NestedFPM, InnerPipeline, VerifyEachPass, 1209 DebugLogging)) 1210 return false; 1211 FPM.addPass(createRepeatedPass(*Count, std::move(NestedFPM))); 1212 return true; 1213 } 1214 // Normal passes can't have pipelines. 1215 return false; 1216 } 1217 1218 // Now expand the basic registered passes from the .inc file. 1219 #define FUNCTION_PASS(NAME, CREATE_PASS) \ 1220 if (Name == NAME) { \ 1221 FPM.addPass(CREATE_PASS); \ 1222 return true; \ 1223 } 1224 #define FUNCTION_ANALYSIS(NAME, CREATE_PASS) \ 1225 if (Name == "require<" NAME ">") { \ 1226 FPM.addPass( \ 1227 RequireAnalysisPass< \ 1228 std::remove_reference<decltype(CREATE_PASS)>::type, Function>()); \ 1229 return true; \ 1230 } \ 1231 if (Name == "invalidate<" NAME ">") { \ 1232 FPM.addPass(InvalidateAnalysisPass< \ 1233 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1234 return true; \ 1235 } 1236 #include "PassRegistry.def" 1237 1238 return false; 1239 } 1240 1241 bool PassBuilder::parseLoopPass(LoopPassManager &LPM, const PipelineElement &E, 1242 bool VerifyEachPass, bool DebugLogging) { 1243 StringRef Name = E.Name; 1244 auto &InnerPipeline = E.InnerPipeline; 1245 1246 // First handle complex passes like the pass managers which carry pipelines. 1247 if (!InnerPipeline.empty()) { 1248 if (Name == "loop") { 1249 LoopPassManager NestedLPM(DebugLogging); 1250 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass, 1251 DebugLogging)) 1252 return false; 1253 // Add the nested pass manager with the appropriate adaptor. 1254 LPM.addPass(std::move(NestedLPM)); 1255 return true; 1256 } 1257 if (auto Count = parseRepeatPassName(Name)) { 1258 LoopPassManager NestedLPM(DebugLogging); 1259 if (!parseLoopPassPipeline(NestedLPM, InnerPipeline, VerifyEachPass, 1260 DebugLogging)) 1261 return false; 1262 LPM.addPass(createRepeatedPass(*Count, std::move(NestedLPM))); 1263 return true; 1264 } 1265 // Normal passes can't have pipelines. 1266 return false; 1267 } 1268 1269 // Now expand the basic registered passes from the .inc file. 1270 #define LOOP_PASS(NAME, CREATE_PASS) \ 1271 if (Name == NAME) { \ 1272 LPM.addPass(CREATE_PASS); \ 1273 return true; \ 1274 } 1275 #define LOOP_ANALYSIS(NAME, CREATE_PASS) \ 1276 if (Name == "require<" NAME ">") { \ 1277 LPM.addPass(RequireAnalysisPass< \ 1278 std::remove_reference<decltype(CREATE_PASS)>::type, Loop, \ 1279 LoopAnalysisManager, LoopStandardAnalysisResults &, \ 1280 LPMUpdater &>()); \ 1281 return true; \ 1282 } \ 1283 if (Name == "invalidate<" NAME ">") { \ 1284 LPM.addPass(InvalidateAnalysisPass< \ 1285 std::remove_reference<decltype(CREATE_PASS)>::type>()); \ 1286 return true; \ 1287 } 1288 #include "PassRegistry.def" 1289 1290 return false; 1291 } 1292 1293 bool PassBuilder::parseAAPassName(AAManager &AA, StringRef Name) { 1294 #define MODULE_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 1295 if (Name == NAME) { \ 1296 AA.registerModuleAnalysis< \ 1297 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 1298 return true; \ 1299 } 1300 #define FUNCTION_ALIAS_ANALYSIS(NAME, CREATE_PASS) \ 1301 if (Name == NAME) { \ 1302 AA.registerFunctionAnalysis< \ 1303 std::remove_reference<decltype(CREATE_PASS)>::type>(); \ 1304 return true; \ 1305 } 1306 #include "PassRegistry.def" 1307 1308 return false; 1309 } 1310 1311 bool PassBuilder::parseLoopPassPipeline(LoopPassManager &LPM, 1312 ArrayRef<PipelineElement> Pipeline, 1313 bool VerifyEachPass, 1314 bool DebugLogging) { 1315 for (const auto &Element : Pipeline) { 1316 if (!parseLoopPass(LPM, Element, VerifyEachPass, DebugLogging)) 1317 return false; 1318 // FIXME: No verifier support for Loop passes! 1319 } 1320 return true; 1321 } 1322 1323 bool PassBuilder::parseFunctionPassPipeline(FunctionPassManager &FPM, 1324 ArrayRef<PipelineElement> Pipeline, 1325 bool VerifyEachPass, 1326 bool DebugLogging) { 1327 for (const auto &Element : Pipeline) { 1328 if (!parseFunctionPass(FPM, Element, VerifyEachPass, DebugLogging)) 1329 return false; 1330 if (VerifyEachPass) 1331 FPM.addPass(VerifierPass()); 1332 } 1333 return true; 1334 } 1335 1336 bool PassBuilder::parseCGSCCPassPipeline(CGSCCPassManager &CGPM, 1337 ArrayRef<PipelineElement> Pipeline, 1338 bool VerifyEachPass, 1339 bool DebugLogging) { 1340 for (const auto &Element : Pipeline) { 1341 if (!parseCGSCCPass(CGPM, Element, VerifyEachPass, DebugLogging)) 1342 return false; 1343 // FIXME: No verifier support for CGSCC passes! 1344 } 1345 return true; 1346 } 1347 1348 void PassBuilder::crossRegisterProxies(LoopAnalysisManager &LAM, 1349 FunctionAnalysisManager &FAM, 1350 CGSCCAnalysisManager &CGAM, 1351 ModuleAnalysisManager &MAM) { 1352 MAM.registerPass([&] { return FunctionAnalysisManagerModuleProxy(FAM); }); 1353 MAM.registerPass([&] { return CGSCCAnalysisManagerModuleProxy(CGAM); }); 1354 CGAM.registerPass([&] { return ModuleAnalysisManagerCGSCCProxy(MAM); }); 1355 FAM.registerPass([&] { return CGSCCAnalysisManagerFunctionProxy(CGAM); }); 1356 FAM.registerPass([&] { return ModuleAnalysisManagerFunctionProxy(MAM); }); 1357 FAM.registerPass([&] { return LoopAnalysisManagerFunctionProxy(LAM); }); 1358 LAM.registerPass([&] { return FunctionAnalysisManagerLoopProxy(FAM); }); 1359 } 1360 1361 bool PassBuilder::parseModulePassPipeline(ModulePassManager &MPM, 1362 ArrayRef<PipelineElement> Pipeline, 1363 bool VerifyEachPass, 1364 bool DebugLogging) { 1365 for (const auto &Element : Pipeline) { 1366 if (!parseModulePass(MPM, Element, VerifyEachPass, DebugLogging)) 1367 return false; 1368 if (VerifyEachPass) 1369 MPM.addPass(VerifierPass()); 1370 } 1371 return true; 1372 } 1373 1374 // Primary pass pipeline description parsing routine. 1375 // FIXME: Should this routine accept a TargetMachine or require the caller to 1376 // pre-populate the analysis managers with target-specific stuff? 1377 bool PassBuilder::parsePassPipeline(ModulePassManager &MPM, 1378 StringRef PipelineText, bool VerifyEachPass, 1379 bool DebugLogging) { 1380 auto Pipeline = parsePipelineText(PipelineText); 1381 if (!Pipeline || Pipeline->empty()) 1382 return false; 1383 1384 // If the first name isn't at the module layer, wrap the pipeline up 1385 // automatically. 1386 StringRef FirstName = Pipeline->front().Name; 1387 1388 if (!isModulePassName(FirstName)) { 1389 if (isCGSCCPassName(FirstName)) 1390 Pipeline = {{"cgscc", std::move(*Pipeline)}}; 1391 else if (isFunctionPassName(FirstName)) 1392 Pipeline = {{"function", std::move(*Pipeline)}}; 1393 else if (isLoopPassName(FirstName)) 1394 Pipeline = {{"function", {{"loop", std::move(*Pipeline)}}}}; 1395 else 1396 // Unknown pass name! 1397 return false; 1398 } 1399 1400 return parseModulePassPipeline(MPM, *Pipeline, VerifyEachPass, DebugLogging); 1401 } 1402 1403 bool PassBuilder::parseAAPipeline(AAManager &AA, StringRef PipelineText) { 1404 // If the pipeline just consists of the word 'default' just replace the AA 1405 // manager with our default one. 1406 if (PipelineText == "default") { 1407 AA = buildDefaultAAPipeline(); 1408 return true; 1409 } 1410 1411 while (!PipelineText.empty()) { 1412 StringRef Name; 1413 std::tie(Name, PipelineText) = PipelineText.split(','); 1414 if (!parseAAPassName(AA, Name)) 1415 return false; 1416 } 1417 1418 return true; 1419 } 1420