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