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