HotColdSplitting.cpp 28 KB

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