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