1 //===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 /// 9 /// \file 10 /// The goal of hot/cold splitting is to improve the memory locality of code. 11 /// The splitting pass does this by identifying cold blocks and moving them into 12 /// separate functions. 13 /// 14 /// When the splitting pass finds a cold block (referred to as "the sink"), it 15 /// grows a maximal cold region around that block. The maximal region contains 16 /// all blocks (post-)dominated by the sink [*]. In theory, these blocks are as 17 /// cold as the sink. Once a region is found, it's split out of the original 18 /// function provided it's profitable to do so. 19 /// 20 /// [*] In practice, there is some added complexity because some blocks are not 21 /// safe to extract. 22 /// 23 /// TODO: Use the PM to get domtrees, and preserve BFI/BPI. 24 /// TODO: Reorder outlined functions. 25 /// 26 //===----------------------------------------------------------------------===// 27 28 #include "llvm/Transforms/IPO/HotColdSplitting.h" 29 #include "llvm/ADT/PostOrderIterator.h" 30 #include "llvm/ADT/SmallVector.h" 31 #include "llvm/ADT/Statistic.h" 32 #include "llvm/Analysis/AliasAnalysis.h" 33 #include "llvm/Analysis/BlockFrequencyInfo.h" 34 #include "llvm/Analysis/BranchProbabilityInfo.h" 35 #include "llvm/Analysis/CFG.h" 36 #include "llvm/Analysis/OptimizationRemarkEmitter.h" 37 #include "llvm/Analysis/PostDominators.h" 38 #include "llvm/Analysis/ProfileSummaryInfo.h" 39 #include "llvm/Analysis/TargetTransformInfo.h" 40 #include "llvm/IR/BasicBlock.h" 41 #include "llvm/IR/CFG.h" 42 #include "llvm/IR/CallSite.h" 43 #include "llvm/IR/DataLayout.h" 44 #include "llvm/IR/DiagnosticInfo.h" 45 #include "llvm/IR/Dominators.h" 46 #include "llvm/IR/Function.h" 47 #include "llvm/IR/Instruction.h" 48 #include "llvm/IR/Instructions.h" 49 #include "llvm/IR/IntrinsicInst.h" 50 #include "llvm/IR/Metadata.h" 51 #include "llvm/IR/Module.h" 52 #include "llvm/IR/PassManager.h" 53 #include "llvm/IR/Type.h" 54 #include "llvm/IR/Use.h" 55 #include "llvm/IR/User.h" 56 #include "llvm/IR/Value.h" 57 #include "llvm/InitializePasses.h" 58 #include "llvm/Pass.h" 59 #include "llvm/Support/BlockFrequency.h" 60 #include "llvm/Support/BranchProbability.h" 61 #include "llvm/Support/Debug.h" 62 #include "llvm/Support/raw_ostream.h" 63 #include "llvm/Transforms/IPO.h" 64 #include "llvm/Transforms/Scalar.h" 65 #include "llvm/Transforms/Utils/BasicBlockUtils.h" 66 #include "llvm/Transforms/Utils/Cloning.h" 67 #include "llvm/Transforms/Utils/CodeExtractor.h" 68 #include "llvm/Transforms/Utils/Local.h" 69 #include "llvm/Transforms/Utils/ValueMapper.h" 70 #include <algorithm> 71 #include <cassert> 72 73 #define DEBUG_TYPE "hotcoldsplit" 74 75 STATISTIC(NumColdRegionsFound, "Number of cold regions found."); 76 STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined."); 77 78 using namespace llvm; 79 80 static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis", 81 cl::init(true), cl::Hidden); 82 83 static cl::opt<int> 84 SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden, 85 cl::desc("Base penalty for splitting cold code (as a " 86 "multiple of TCC_Basic)")); 87 88 namespace { 89 // Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify 90 // this function unless you modify the MBB version as well. 91 // 92 /// A no successor, non-return block probably ends in unreachable and is cold. 93 /// Also consider a block that ends in an indirect branch to be a return block, 94 /// since many targets use plain indirect branches to return. 95 bool blockEndsInUnreachable(const BasicBlock &BB) { 96 if (!succ_empty(&BB)) 97 return false; 98 if (BB.empty()) 99 return true; 100 const Instruction *I = BB.getTerminator(); 101 return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I)); 102 } 103 104 bool unlikelyExecuted(BasicBlock &BB) { 105 // Exception handling blocks are unlikely executed. 106 if (BB.isEHPad() || isa<ResumeInst>(BB.getTerminator())) 107 return true; 108 109 // The block is cold if it calls/invokes a cold function. However, do not 110 // mark sanitizer traps as cold. 111 for (Instruction &I : BB) 112 if (auto CS = CallSite(&I)) 113 if (CS.hasFnAttr(Attribute::Cold) && !CS->getMetadata("nosanitize")) 114 return true; 115 116 // The block is cold if it has an unreachable terminator, unless it's 117 // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp). 118 if (blockEndsInUnreachable(BB)) { 119 if (auto *CI = 120 dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode())) 121 if (CI->hasFnAttr(Attribute::NoReturn)) 122 return false; 123 return true; 124 } 125 126 return false; 127 } 128 129 /// Check whether it's safe to outline \p BB. 130 static bool mayExtractBlock(const BasicBlock &BB) { 131 // EH pads are unsafe to outline because doing so breaks EH type tables. It 132 // follows that invoke instructions cannot be extracted, because CodeExtractor 133 // requires unwind destinations to be within the extraction region. 134 // 135 // Resumes that are not reachable from a cleanup landing pad are considered to 136 // be unreachable. It’s not safe to split them out either. 137 auto Term = BB.getTerminator(); 138 return !BB.hasAddressTaken() && !BB.isEHPad() && !isa<InvokeInst>(Term) && 139 !isa<ResumeInst>(Term); 140 } 141 142 /// Mark \p F cold. Based on this assumption, also optimize it for minimum size. 143 /// If \p UpdateEntryCount is true (set when this is a new split function and 144 /// module has profile data), set entry count to 0 to ensure treated as cold. 145 /// Return true if the function is changed. 146 static bool markFunctionCold(Function &F, bool UpdateEntryCount = false) { 147 assert(!F.hasOptNone() && "Can't mark this cold"); 148 bool Changed = false; 149 if (!F.hasFnAttribute(Attribute::Cold)) { 150 F.addFnAttr(Attribute::Cold); 151 Changed = true; 152 } 153 if (!F.hasFnAttribute(Attribute::MinSize)) { 154 F.addFnAttr(Attribute::MinSize); 155 Changed = true; 156 } 157 if (UpdateEntryCount) { 158 // Set the entry count to 0 to ensure it is placed in the unlikely text 159 // section when function sections are enabled. 160 F.setEntryCount(0); 161 Changed = true; 162 } 163 164 return Changed; 165 } 166 167 class HotColdSplittingLegacyPass : public ModulePass { 168 public: 169 static char ID; 170 HotColdSplittingLegacyPass() : ModulePass(ID) { 171 initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry()); 172 } 173 174 void getAnalysisUsage(AnalysisUsage &AU) const override { 175 AU.addRequired<BlockFrequencyInfoWrapperPass>(); 176 AU.addRequired<ProfileSummaryInfoWrapperPass>(); 177 AU.addRequired<TargetTransformInfoWrapperPass>(); 178 AU.addUsedIfAvailable<AssumptionCacheTracker>(); 179 } 180 181 bool runOnModule(Module &M) override; 182 }; 183 184 } // end anonymous namespace 185 186 /// Check whether \p F is inherently cold. 187 bool HotColdSplitting::isFunctionCold(const Function &F) const { 188 if (F.hasFnAttribute(Attribute::Cold)) 189 return true; 190 191 if (F.getCallingConv() == CallingConv::Cold) 192 return true; 193 194 if (PSI->isFunctionEntryCold(&F)) 195 return true; 196 197 return false; 198 } 199 200 // Returns false if the function should not be considered for hot-cold split 201 // optimization. 202 bool HotColdSplitting::shouldOutlineFrom(const Function &F) const { 203 if (F.hasFnAttribute(Attribute::AlwaysInline)) 204 return false; 205 206 if (F.hasFnAttribute(Attribute::NoInline)) 207 return false; 208 209 if (F.hasFnAttribute(Attribute::SanitizeAddress) || 210 F.hasFnAttribute(Attribute::SanitizeHWAddress) || 211 F.hasFnAttribute(Attribute::SanitizeThread) || 212 F.hasFnAttribute(Attribute::SanitizeMemory)) 213 return false; 214 215 return true; 216 } 217 218 /// Get the benefit score of outlining \p Region. 219 static int getOutliningBenefit(ArrayRef<BasicBlock *> Region, 220 TargetTransformInfo &TTI) { 221 // Sum up the code size costs of non-terminator instructions. Tight coupling 222 // with \ref getOutliningPenalty is needed to model the costs of terminators. 223 int Benefit = 0; 224 for (BasicBlock *BB : Region) 225 for (Instruction &I : BB->instructionsWithoutDebug()) 226 if (&I != BB->getTerminator()) 227 Benefit += 228 TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize); 229 230 return Benefit; 231 } 232 233 /// Get the penalty score for outlining \p Region. 234 static int getOutliningPenalty(ArrayRef<BasicBlock *> Region, 235 unsigned NumInputs, unsigned NumOutputs) { 236 int Penalty = SplittingThreshold; 237 LLVM_DEBUG(dbgs() << "Applying penalty for splitting: " << Penalty << "\n"); 238 239 // If the splitting threshold is set at or below zero, skip the usual 240 // profitability check. 241 if (SplittingThreshold <= 0) 242 return Penalty; 243 244 // The typical code size cost for materializing an argument for the outlined 245 // call. 246 LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumInputs << " inputs\n"); 247 const int CostForArgMaterialization = TargetTransformInfo::TCC_Basic; 248 Penalty += CostForArgMaterialization * NumInputs; 249 250 // The typical code size cost for an output alloca, its associated store, and 251 // its associated reload. 252 LLVM_DEBUG(dbgs() << "Applying penalty for: " << NumOutputs << " outputs\n"); 253 const int CostForRegionOutput = 3 * TargetTransformInfo::TCC_Basic; 254 Penalty += CostForRegionOutput * NumOutputs; 255 256 // Find the number of distinct exit blocks for the region. Use a conservative 257 // check to determine whether control returns from the region. 258 bool NoBlocksReturn = true; 259 SmallPtrSet<BasicBlock *, 2> SuccsOutsideRegion; 260 for (BasicBlock *BB : Region) { 261 // If a block has no successors, only assume it does not return if it's 262 // unreachable. 263 if (succ_empty(BB)) { 264 NoBlocksReturn &= isa<UnreachableInst>(BB->getTerminator()); 265 continue; 266 } 267 268 for (BasicBlock *SuccBB : successors(BB)) { 269 if (find(Region, SuccBB) == Region.end()) { 270 NoBlocksReturn = false; 271 SuccsOutsideRegion.insert(SuccBB); 272 } 273 } 274 } 275 276 // Apply a `noreturn` bonus. 277 if (NoBlocksReturn) { 278 LLVM_DEBUG(dbgs() << "Applying bonus for: " << Region.size() 279 << " non-returning terminators\n"); 280 Penalty -= Region.size(); 281 } 282 283 // Apply a penalty for having more than one successor outside of the region. 284 // This penalty accounts for the switch needed in the caller. 285 if (!SuccsOutsideRegion.empty()) { 286 LLVM_DEBUG(dbgs() << "Applying penalty for: " << SuccsOutsideRegion.size() 287 << " non-region successors\n"); 288 Penalty += (SuccsOutsideRegion.size() - 1) * TargetTransformInfo::TCC_Basic; 289 } 290 291 return Penalty; 292 } 293 294 Function *HotColdSplitting::extractColdRegion( 295 const BlockSequence &Region, const CodeExtractorAnalysisCache &CEAC, 296 DominatorTree &DT, BlockFrequencyInfo *BFI, TargetTransformInfo &TTI, 297 OptimizationRemarkEmitter &ORE, AssumptionCache *AC, unsigned Count) { 298 assert(!Region.empty()); 299 300 // TODO: Pass BFI and BPI to update profile information. 301 CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr, 302 /* BPI */ nullptr, AC, /* AllowVarArgs */ false, 303 /* AllowAlloca */ false, 304 /* Suffix */ "cold." + std::to_string(Count)); 305 306 // Perform a simple cost/benefit analysis to decide whether or not to permit 307 // splitting. 308 SetVector<Value *> Inputs, Outputs, Sinks; 309 CE.findInputsOutputs(Inputs, Outputs, Sinks); 310 int OutliningBenefit = getOutliningBenefit(Region, TTI); 311 int OutliningPenalty = 312 getOutliningPenalty(Region, Inputs.size(), Outputs.size()); 313 LLVM_DEBUG(dbgs() << "Split profitability: benefit = " << OutliningBenefit 314 << ", penalty = " << OutliningPenalty << "\n"); 315 if (OutliningBenefit <= OutliningPenalty) 316 return nullptr; 317 318 Function *OrigF = Region[0]->getParent(); 319 if (Function *OutF = CE.extractCodeRegion(CEAC)) { 320 User *U = *OutF->user_begin(); 321 CallInst *CI = cast<CallInst>(U); 322 CallSite CS(CI); 323 NumColdRegionsOutlined++; 324 if (TTI.useColdCCForColdCall(*OutF)) { 325 OutF->setCallingConv(CallingConv::Cold); 326 CS.setCallingConv(CallingConv::Cold); 327 } 328 CI->setIsNoInline(); 329 330 markFunctionCold(*OutF, BFI != nullptr); 331 332 LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF); 333 ORE.emit([&]() { 334 return OptimizationRemark(DEBUG_TYPE, "HotColdSplit", 335 &*Region[0]->begin()) 336 << ore::NV("Original", OrigF) << " split cold code into " 337 << ore::NV("Split", OutF); 338 }); 339 return OutF; 340 } 341 342 ORE.emit([&]() { 343 return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed", 344 &*Region[0]->begin()) 345 << "Failed to extract region at block " 346 << ore::NV("Block", Region.front()); 347 }); 348 return nullptr; 349 } 350 351 /// A pair of (basic block, score). 352 using BlockTy = std::pair<BasicBlock *, unsigned>; 353 354 namespace { 355 /// A maximal outlining region. This contains all blocks post-dominated by a 356 /// sink block, the sink block itself, and all blocks dominated by the sink. 357 /// If sink-predecessors and sink-successors cannot be extracted in one region, 358 /// the static constructor returns a list of suitable extraction regions. 359 class OutliningRegion { 360 /// A list of (block, score) pairs. A block's score is non-zero iff it's a 361 /// viable sub-region entry point. Blocks with higher scores are better entry 362 /// points (i.e. they are more distant ancestors of the sink block). 363 SmallVector<BlockTy, 0> Blocks = {}; 364 365 /// The suggested entry point into the region. If the region has multiple 366 /// entry points, all blocks within the region may not be reachable from this 367 /// entry point. 368 BasicBlock *SuggestedEntryPoint = nullptr; 369 370 /// Whether the entire function is cold. 371 bool EntireFunctionCold = false; 372 373 /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise. 374 static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) { 375 return mayExtractBlock(BB) ? Score : 0; 376 } 377 378 /// These scores should be lower than the score for predecessor blocks, 379 /// because regions starting at predecessor blocks are typically larger. 380 static constexpr unsigned ScoreForSuccBlock = 1; 381 static constexpr unsigned ScoreForSinkBlock = 1; 382 383 OutliningRegion(const OutliningRegion &) = delete; 384 OutliningRegion &operator=(const OutliningRegion &) = delete; 385 386 public: 387 OutliningRegion() = default; 388 OutliningRegion(OutliningRegion &&) = default; 389 OutliningRegion &operator=(OutliningRegion &&) = default; 390 391 static std::vector<OutliningRegion> create(BasicBlock &SinkBB, 392 const DominatorTree &DT, 393 const PostDominatorTree &PDT) { 394 std::vector<OutliningRegion> Regions; 395 SmallPtrSet<BasicBlock *, 4> RegionBlocks; 396 397 Regions.emplace_back(); 398 OutliningRegion *ColdRegion = &Regions.back(); 399 400 auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) { 401 RegionBlocks.insert(BB); 402 ColdRegion->Blocks.emplace_back(BB, Score); 403 }; 404 405 // The ancestor farthest-away from SinkBB, and also post-dominated by it. 406 unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock); 407 ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr; 408 unsigned BestScore = SinkScore; 409 410 // Visit SinkBB's ancestors using inverse DFS. 411 auto PredIt = ++idf_begin(&SinkBB); 412 auto PredEnd = idf_end(&SinkBB); 413 while (PredIt != PredEnd) { 414 BasicBlock &PredBB = **PredIt; 415 bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB); 416 417 // If the predecessor is cold and has no predecessors, the entire 418 // function must be cold. 419 if (SinkPostDom && pred_empty(&PredBB)) { 420 ColdRegion->EntireFunctionCold = true; 421 return Regions; 422 } 423 424 // If SinkBB does not post-dominate a predecessor, do not mark the 425 // predecessor (or any of its predecessors) cold. 426 if (!SinkPostDom || !mayExtractBlock(PredBB)) { 427 PredIt.skipChildren(); 428 continue; 429 } 430 431 // Keep track of the post-dominated ancestor farthest away from the sink. 432 // The path length is always >= 2, ensuring that predecessor blocks are 433 // considered as entry points before the sink block. 434 unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength()); 435 if (PredScore > BestScore) { 436 ColdRegion->SuggestedEntryPoint = &PredBB; 437 BestScore = PredScore; 438 } 439 440 addBlockToRegion(&PredBB, PredScore); 441 ++PredIt; 442 } 443 444 // If the sink can be added to the cold region, do so. It's considered as 445 // an entry point before any sink-successor blocks. 446 // 447 // Otherwise, split cold sink-successor blocks using a separate region. 448 // This satisfies the requirement that all extraction blocks other than the 449 // first have predecessors within the extraction region. 450 if (mayExtractBlock(SinkBB)) { 451 addBlockToRegion(&SinkBB, SinkScore); 452 } else { 453 Regions.emplace_back(); 454 ColdRegion = &Regions.back(); 455 BestScore = 0; 456 } 457 458 // Find all successors of SinkBB dominated by SinkBB using DFS. 459 auto SuccIt = ++df_begin(&SinkBB); 460 auto SuccEnd = df_end(&SinkBB); 461 while (SuccIt != SuccEnd) { 462 BasicBlock &SuccBB = **SuccIt; 463 bool SinkDom = DT.dominates(&SinkBB, &SuccBB); 464 465 // Don't allow the backwards & forwards DFSes to mark the same block. 466 bool DuplicateBlock = RegionBlocks.count(&SuccBB); 467 468 // If SinkBB does not dominate a successor, do not mark the successor (or 469 // any of its successors) cold. 470 if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) { 471 SuccIt.skipChildren(); 472 continue; 473 } 474 475 unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock); 476 if (SuccScore > BestScore) { 477 ColdRegion->SuggestedEntryPoint = &SuccBB; 478 BestScore = SuccScore; 479 } 480 481 addBlockToRegion(&SuccBB, SuccScore); 482 ++SuccIt; 483 } 484 485 return Regions; 486 } 487 488 /// Whether this region has nothing to extract. 489 bool empty() const { return !SuggestedEntryPoint; } 490 491 /// The blocks in this region. 492 ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; } 493 494 /// Whether the entire function containing this region is cold. 495 bool isEntireFunctionCold() const { return EntireFunctionCold; } 496 497 /// Remove a sub-region from this region and return it as a block sequence. 498 BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) { 499 assert(!empty() && !isEntireFunctionCold() && "Nothing to extract"); 500 501 // Remove blocks dominated by the suggested entry point from this region. 502 // During the removal, identify the next best entry point into the region. 503 // Ensure that the first extracted block is the suggested entry point. 504 BlockSequence SubRegion = {SuggestedEntryPoint}; 505 BasicBlock *NextEntryPoint = nullptr; 506 unsigned NextScore = 0; 507 auto RegionEndIt = Blocks.end(); 508 auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) { 509 BasicBlock *BB = Block.first; 510 unsigned Score = Block.second; 511 bool InSubRegion = 512 BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB); 513 if (!InSubRegion && Score > NextScore) { 514 NextEntryPoint = BB; 515 NextScore = Score; 516 } 517 if (InSubRegion && BB != SuggestedEntryPoint) 518 SubRegion.push_back(BB); 519 return InSubRegion; 520 }); 521 Blocks.erase(RegionStartIt, RegionEndIt); 522 523 // Update the suggested entry point. 524 SuggestedEntryPoint = NextEntryPoint; 525 526 return SubRegion; 527 } 528 }; 529 } // namespace 530 531 bool HotColdSplitting::outlineColdRegions(Function &F, bool HasProfileSummary) { 532 bool Changed = false; 533 534 // The set of cold blocks. 535 SmallPtrSet<BasicBlock *, 4> ColdBlocks; 536 537 // The worklist of non-intersecting regions left to outline. 538 SmallVector<OutliningRegion, 2> OutliningWorklist; 539 540 // Set up an RPO traversal. Experimentally, this performs better (outlines 541 // more) than a PO traversal, because we prevent region overlap by keeping 542 // the first region to contain a block. 543 ReversePostOrderTraversal<Function *> RPOT(&F); 544 545 // Calculate domtrees lazily. This reduces compile-time significantly. 546 std::unique_ptr<DominatorTree> DT; 547 std::unique_ptr<PostDominatorTree> PDT; 548 549 // Calculate BFI lazily (it's only used to query ProfileSummaryInfo). This 550 // reduces compile-time significantly. TODO: When we *do* use BFI, we should 551 // be able to salvage its domtrees instead of recomputing them. 552 BlockFrequencyInfo *BFI = nullptr; 553 if (HasProfileSummary) 554 BFI = GetBFI(F); 555 556 TargetTransformInfo &TTI = GetTTI(F); 557 OptimizationRemarkEmitter &ORE = (*GetORE)(F); 558 AssumptionCache *AC = LookupAC(F); 559 560 // Find all cold regions. 561 for (BasicBlock *BB : RPOT) { 562 // This block is already part of some outlining region. 563 if (ColdBlocks.count(BB)) 564 continue; 565 566 bool Cold = (BFI && PSI->isColdBlock(BB, BFI)) || 567 (EnableStaticAnalyis && unlikelyExecuted(*BB)); 568 if (!Cold) 569 continue; 570 571 LLVM_DEBUG({ 572 dbgs() << "Found a cold block:\n"; 573 BB->dump(); 574 }); 575 576 if (!DT) 577 DT = std::make_unique<DominatorTree>(F); 578 if (!PDT) 579 PDT = std::make_unique<PostDominatorTree>(F); 580 581 auto Regions = OutliningRegion::create(*BB, *DT, *PDT); 582 for (OutliningRegion &Region : Regions) { 583 if (Region.empty()) 584 continue; 585 586 if (Region.isEntireFunctionCold()) { 587 LLVM_DEBUG(dbgs() << "Entire function is cold\n"); 588 return markFunctionCold(F); 589 } 590 591 // If this outlining region intersects with another, drop the new region. 592 // 593 // TODO: It's theoretically possible to outline more by only keeping the 594 // largest region which contains a block, but the extra bookkeeping to do 595 // this is tricky/expensive. 596 bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) { 597 return !ColdBlocks.insert(Block.first).second; 598 }); 599 if (RegionsOverlap) 600 continue; 601 602 OutliningWorklist.emplace_back(std::move(Region)); 603 ++NumColdRegionsFound; 604 } 605 } 606 607 if (OutliningWorklist.empty()) 608 return Changed; 609 610 // Outline single-entry cold regions, splitting up larger regions as needed. 611 unsigned OutlinedFunctionID = 1; 612 // Cache and recycle the CodeExtractor analysis to avoid O(n^2) compile-time. 613 CodeExtractorAnalysisCache CEAC(F); 614 do { 615 OutliningRegion Region = OutliningWorklist.pop_back_val(); 616 assert(!Region.empty() && "Empty outlining region in worklist"); 617 do { 618 BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT); 619 LLVM_DEBUG({ 620 dbgs() << "Hot/cold splitting attempting to outline these blocks:\n"; 621 for (BasicBlock *BB : SubRegion) 622 BB->dump(); 623 }); 624 625 Function *Outlined = extractColdRegion(SubRegion, CEAC, *DT, BFI, TTI, 626 ORE, AC, OutlinedFunctionID); 627 if (Outlined) { 628 ++OutlinedFunctionID; 629 Changed = true; 630 } 631 } while (!Region.empty()); 632 } while (!OutliningWorklist.empty()); 633 634 return Changed; 635 } 636 637 bool HotColdSplitting::run(Module &M) { 638 bool Changed = false; 639 bool HasProfileSummary = (M.getProfileSummary(/* IsCS */ false) != nullptr); 640 for (auto It = M.begin(), End = M.end(); It != End; ++It) { 641 Function &F = *It; 642 643 // Do not touch declarations. 644 if (F.isDeclaration()) 645 continue; 646 647 // Do not modify `optnone` functions. 648 if (F.hasOptNone()) 649 continue; 650 651 // Detect inherently cold functions and mark them as such. 652 if (isFunctionCold(F)) { 653 Changed |= markFunctionCold(F); 654 continue; 655 } 656 657 if (!shouldOutlineFrom(F)) { 658 LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n"); 659 continue; 660 } 661 662 LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n"); 663 Changed |= outlineColdRegions(F, HasProfileSummary); 664 } 665 return Changed; 666 } 667 668 bool HotColdSplittingLegacyPass::runOnModule(Module &M) { 669 if (skipModule(M)) 670 return false; 671 ProfileSummaryInfo *PSI = 672 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI(); 673 auto GTTI = [this](Function &F) -> TargetTransformInfo & { 674 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F); 675 }; 676 auto GBFI = [this](Function &F) { 677 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI(); 678 }; 679 std::unique_ptr<OptimizationRemarkEmitter> ORE; 680 std::function<OptimizationRemarkEmitter &(Function &)> GetORE = 681 [&ORE](Function &F) -> OptimizationRemarkEmitter & { 682 ORE.reset(new OptimizationRemarkEmitter(&F)); 683 return *ORE.get(); 684 }; 685 auto LookupAC = [this](Function &F) -> AssumptionCache * { 686 if (auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>()) 687 return ACT->lookupAssumptionCache(F); 688 return nullptr; 689 }; 690 691 return HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M); 692 } 693 694 PreservedAnalyses 695 HotColdSplittingPass::run(Module &M, ModuleAnalysisManager &AM) { 696 auto &FAM = AM.getResult<FunctionAnalysisManagerModuleProxy>(M).getManager(); 697 698 auto LookupAC = [&FAM](Function &F) -> AssumptionCache * { 699 return FAM.getCachedResult<AssumptionAnalysis>(F); 700 }; 701 702 auto GBFI = [&FAM](Function &F) { 703 return &FAM.getResult<BlockFrequencyAnalysis>(F); 704 }; 705 706 std::function<TargetTransformInfo &(Function &)> GTTI = 707 [&FAM](Function &F) -> TargetTransformInfo & { 708 return FAM.getResult<TargetIRAnalysis>(F); 709 }; 710 711 std::unique_ptr<OptimizationRemarkEmitter> ORE; 712 std::function<OptimizationRemarkEmitter &(Function &)> GetORE = 713 [&ORE](Function &F) -> OptimizationRemarkEmitter & { 714 ORE.reset(new OptimizationRemarkEmitter(&F)); 715 return *ORE.get(); 716 }; 717 718 ProfileSummaryInfo *PSI = &AM.getResult<ProfileSummaryAnalysis>(M); 719 720 if (HotColdSplitting(PSI, GBFI, GTTI, &GetORE, LookupAC).run(M)) 721 return PreservedAnalyses::none(); 722 return PreservedAnalyses::all(); 723 } 724 725 char HotColdSplittingLegacyPass::ID = 0; 726 INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit", 727 "Hot Cold Splitting", false, false) 728 INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass) 729 INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass) 730 INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit", 731 "Hot Cold Splitting", false, false) 732 733 ModulePass *llvm::createHotColdSplittingPass() { 734 return new HotColdSplittingLegacyPass(); 735 } 736