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