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