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