blob: a6ea04e43e887f539c2ae91997f618dd9b633693 [file] [log] [blame]
Aditya Kumar801394a2018-09-07 15:03:49 +00001//===- HotColdSplitting.cpp -- Outline Cold Regions -------------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// Outline cold regions to a separate function.
11// TODO: Update BFI and BPI
12// TODO: Add all the outlined functions to a separate section.
13//
14//===----------------------------------------------------------------------===//
15
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"
Sebastian Popa1f20fc2018-09-10 15:08:02 +000025#include "llvm/Analysis/TargetTransformInfo.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000026#include "llvm/IR/BasicBlock.h"
27#include "llvm/IR/CFG.h"
28#include "llvm/IR/DataLayout.h"
29#include "llvm/IR/DiagnosticInfo.h"
30#include "llvm/IR/Dominators.h"
31#include "llvm/IR/Function.h"
32#include "llvm/IR/Instruction.h"
33#include "llvm/IR/Instructions.h"
34#include "llvm/IR/Metadata.h"
35#include "llvm/IR/Module.h"
36#include "llvm/IR/PassManager.h"
37#include "llvm/IR/Type.h"
38#include "llvm/IR/Use.h"
39#include "llvm/IR/User.h"
40#include "llvm/IR/Value.h"
41#include "llvm/Pass.h"
42#include "llvm/Support/BlockFrequency.h"
43#include "llvm/Support/BranchProbability.h"
44#include "llvm/Support/Debug.h"
45#include "llvm/Support/raw_ostream.h"
46#include "llvm/Transforms/IPO.h"
47#include "llvm/Transforms/Scalar.h"
48#include "llvm/Transforms/Utils/BasicBlockUtils.h"
49#include "llvm/Transforms/Utils/Cloning.h"
50#include "llvm/Transforms/Utils/CodeExtractor.h"
51#include "llvm/Transforms/Utils/Local.h"
52#include "llvm/Transforms/Utils/SSAUpdater.h"
53#include "llvm/Transforms/Utils/ValueMapper.h"
54#include <algorithm>
55#include <cassert>
56
57#define DEBUG_TYPE "hotcoldsplit"
58
59STATISTIC(NumColdSESEFound,
60 "Number of cold single entry single exit (SESE) regions found.");
61STATISTIC(NumColdSESEOutlined,
62 "Number of cold single entry single exit (SESE) regions outlined.");
63
64using namespace llvm;
65
66static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis",
67 cl::init(true), cl::Hidden);
68
69
70namespace {
71
72struct PostDomTree : PostDomTreeBase<BasicBlock> {
73 PostDomTree(Function &F) { recalculate(F); }
74};
75
76typedef DenseSet<const BasicBlock *> DenseSetBB;
Sebastian Pop12171602018-09-14 20:36:10 +000077typedef DenseMap<const BasicBlock *, uint64_t> DenseMapBBInt;
Aditya Kumar801394a2018-09-07 15:03:49 +000078
79// From: https://reviews.llvm.org/D22558
80// Exit is not part of the region.
81static bool isSingleEntrySingleExit(BasicBlock *Entry, const BasicBlock *Exit,
82 DominatorTree *DT, PostDomTree *PDT,
83 SmallVectorImpl<BasicBlock *> &Region) {
84 if (!DT->dominates(Entry, Exit))
85 return false;
86
87 if (!PDT->dominates(Exit, Entry))
88 return false;
89
90 Region.push_back(Entry);
91 for (auto I = df_begin(Entry), E = df_end(Entry); I != E;) {
92 if (*I == Exit) {
93 I.skipChildren();
94 continue;
95 }
96 if (!DT->dominates(Entry, *I))
97 return false;
98 Region.push_back(*I);
99 ++I;
100 }
101 return true;
102}
103
104bool blockEndsInUnreachable(const BasicBlock &BB) {
105 if (BB.empty())
106 return true;
107 const TerminatorInst *I = BB.getTerminator();
108 if (isa<ReturnInst>(I) || isa<IndirectBrInst>(I))
109 return true;
110 // Unreachable blocks do not have any successor.
111 return succ_empty(&BB);
112}
113
114static
115bool unlikelyExecuted(const BasicBlock &BB) {
116 if (blockEndsInUnreachable(BB))
117 return true;
118 // Exception handling blocks are unlikely executed.
119 if (BB.isEHPad())
120 return true;
121 for (const Instruction &I : BB)
122 if (const CallInst *CI = dyn_cast<CallInst>(&I)) {
123 // The block is cold if it calls functions tagged as cold or noreturn.
124 if (CI->hasFnAttr(Attribute::Cold) ||
125 CI->hasFnAttr(Attribute::NoReturn))
126 return true;
127
128 // Assume that inline assembly is hot code.
129 if (isa<InlineAsm>(CI->getCalledValue()))
130 return false;
131 }
132 return false;
133}
134
135static DenseSetBB getHotBlocks(Function &F) {
Sebastian Pop12171602018-09-14 20:36:10 +0000136
137 // Mark all cold basic blocks.
138 DenseSetBB ColdBlocks;
Aditya Kumar801394a2018-09-07 15:03:49 +0000139 for (BasicBlock &BB : F)
140 if (unlikelyExecuted(BB))
Sebastian Pop12171602018-09-14 20:36:10 +0000141 ColdBlocks.insert((const BasicBlock *)&BB);
142
143 // Forward propagation: basic blocks are hot when they are reachable from the
144 // beginning of the function through a path that does not contain cold blocks.
Aditya Kumar801394a2018-09-07 15:03:49 +0000145 SmallVector<const BasicBlock *, 8> WL;
Sebastian Pop12171602018-09-14 20:36:10 +0000146 DenseSetBB HotBlocks;
Aditya Kumar801394a2018-09-07 15:03:49 +0000147
148 const BasicBlock *It = &F.front();
Aditya Kumar801394a2018-09-07 15:03:49 +0000149 if (!ColdBlocks.count(It)) {
Sebastian Pop12171602018-09-14 20:36:10 +0000150 HotBlocks.insert(It);
151 // Breadth First Search to mark edges reachable from hot.
Aditya Kumar801394a2018-09-07 15:03:49 +0000152 WL.push_back(It);
153 while (WL.size() > 0) {
154 It = WL.pop_back_val();
Sebastian Pop12171602018-09-14 20:36:10 +0000155
156 for (const BasicBlock *Succ : successors(It)) {
Aditya Kumar801394a2018-09-07 15:03:49 +0000157 // Do not visit blocks that are cold.
Sebastian Pop12171602018-09-14 20:36:10 +0000158 if (!ColdBlocks.count(Succ) && !HotBlocks.count(Succ)) {
159 HotBlocks.insert(Succ);
Aditya Kumar801394a2018-09-07 15:03:49 +0000160 WL.push_back(Succ);
161 }
162 }
163 }
164 }
165
Sebastian Pop12171602018-09-14 20:36:10 +0000166 assert(WL.empty() && "work list should be empty");
167
168 DenseMapBBInt NumHotSuccessors;
169 // Back propagation: when all successors of a basic block are cold, the
170 // basic block is cold as well.
171 for (BasicBlock &BBRef : F) {
172 const BasicBlock *BB = &BBRef;
173 if (HotBlocks.count(BB)) {
174 // Keep a count of hot successors for every hot block.
175 NumHotSuccessors[BB] = 0;
176 for (const BasicBlock *Succ : successors(BB))
177 if (!ColdBlocks.count(Succ))
178 NumHotSuccessors[BB] += 1;
179
180 // Add to work list the blocks with all successors cold. Those are the
181 // root nodes in the next loop, where we will move those blocks from
182 // HotBlocks to ColdBlocks and iterate over their predecessors.
183 if (NumHotSuccessors[BB] == 0)
184 WL.push_back(BB);
185 }
186 }
187
188 while (WL.size() > 0) {
189 It = WL.pop_back_val();
190 if (ColdBlocks.count(It))
191 continue;
192
193 // Move the block from HotBlocks to ColdBlocks.
194 HotBlocks.erase(It);
195 ColdBlocks.insert(It);
196
197 // Iterate over the predecessors.
198 for (const BasicBlock *Pred : predecessors(It)) {
199 if (HotBlocks.count(Pred)) {
200 NumHotSuccessors[Pred] -= 1;
201
202 // If Pred has no more hot successors, add it to the work list.
203 if (NumHotSuccessors[Pred] == 0)
204 WL.push_back(Pred);
205 }
206 }
207 }
208
209 return HotBlocks;
Aditya Kumar801394a2018-09-07 15:03:49 +0000210}
211
212class HotColdSplitting {
213public:
214 HotColdSplitting(ProfileSummaryInfo *ProfSI,
215 function_ref<BlockFrequencyInfo *(Function &)> GBFI,
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000216 function_ref<TargetTransformInfo &(Function &)> GTTI,
Aditya Kumar801394a2018-09-07 15:03:49 +0000217 std::function<OptimizationRemarkEmitter &(Function &)> *GORE)
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000218 : PSI(ProfSI), GetBFI(GBFI), GetTTI(GTTI), GetORE(GORE) {}
Aditya Kumar801394a2018-09-07 15:03:49 +0000219 bool run(Module &M);
220
221private:
222 bool shouldOutlineFrom(const Function &F) const;
223 Function *outlineColdBlocks(Function &F,
Sebastian Pop12171602018-09-14 20:36:10 +0000224 const DenseSetBB &ColdBlock,
Aditya Kumar801394a2018-09-07 15:03:49 +0000225 DominatorTree *DT, PostDomTree *PDT);
226 Function *extractColdRegion(const SmallVectorImpl<BasicBlock *> &Region,
227 DominatorTree *DT, BlockFrequencyInfo *BFI,
228 OptimizationRemarkEmitter &ORE);
229 bool isOutlineCandidate(const SmallVectorImpl<BasicBlock *> &Region,
230 const BasicBlock *Exit) const {
231 if (!Exit)
232 return false;
233 // TODO: Find a better metric to compute the size of region being outlined.
234 if (Region.size() == 1)
235 return false;
236 // Regions with landing pads etc.
237 for (const BasicBlock *BB : Region) {
238 if (BB->isEHPad() || BB->hasAddressTaken())
239 return false;
240 }
241 return true;
242 }
243 SmallPtrSet<const Function *, 2> OutlinedFunctions;
244 ProfileSummaryInfo *PSI;
245 function_ref<BlockFrequencyInfo *(Function &)> GetBFI;
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000246 function_ref<TargetTransformInfo &(Function &)> GetTTI;
Aditya Kumar801394a2018-09-07 15:03:49 +0000247 std::function<OptimizationRemarkEmitter &(Function &)> *GetORE;
248};
249
250class HotColdSplittingLegacyPass : public ModulePass {
251public:
252 static char ID;
253 HotColdSplittingLegacyPass() : ModulePass(ID) {
254 initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
255 }
256
257 void getAnalysisUsage(AnalysisUsage &AU) const override {
258 AU.addRequired<AssumptionCacheTracker>();
259 AU.addRequired<BlockFrequencyInfoWrapperPass>();
260 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000261 AU.addRequired<TargetTransformInfoWrapperPass>();
Aditya Kumar801394a2018-09-07 15:03:49 +0000262 }
263
264 bool runOnModule(Module &M) override;
265};
266
267} // end anonymous namespace
268
269// Returns false if the function should not be considered for hot-cold split
270// optimization. Already outlined functions have coldcc so no need to check
271// for them here.
272bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
273 if (F.size() <= 2)
274 return false;
275
276 if (F.hasAddressTaken())
277 return false;
278
279 if (F.hasFnAttribute(Attribute::AlwaysInline))
280 return false;
281
282 if (F.hasFnAttribute(Attribute::NoInline))
283 return false;
284
285 if (F.getCallingConv() == CallingConv::Cold)
286 return false;
287
288 if (PSI->isFunctionEntryCold(&F))
289 return false;
290 return true;
291}
292
293Function *
294HotColdSplitting::extractColdRegion(const SmallVectorImpl<BasicBlock *> &Region,
295 DominatorTree *DT, BlockFrequencyInfo *BFI,
296 OptimizationRemarkEmitter &ORE) {
297 LLVM_DEBUG(for (auto *BB : Region)
298 llvm::dbgs() << "\nExtracting: " << *BB;);
Sebastian Pop12171602018-09-14 20:36:10 +0000299
Aditya Kumar801394a2018-09-07 15:03:49 +0000300 // TODO: Pass BFI and BPI to update profile information.
Sebastian Pop12171602018-09-14 20:36:10 +0000301 CodeExtractor CE(Region, DT);
Aditya Kumar801394a2018-09-07 15:03:49 +0000302
303 SetVector<Value *> Inputs, Outputs, Sinks;
304 CE.findInputsOutputs(Inputs, Outputs, Sinks);
305
306 // Do not extract regions that have live exit variables.
307 if (Outputs.size() > 0)
308 return nullptr;
309
310 if (Function *OutF = CE.extractCodeRegion()) {
311 User *U = *OutF->user_begin();
312 CallInst *CI = cast<CallInst>(U);
313 CallSite CS(CI);
314 NumColdSESEOutlined++;
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000315 if (GetTTI(*OutF).useColdCCForColdCall(*OutF)) {
316 OutF->setCallingConv(CallingConv::Cold);
317 CS.setCallingConv(CallingConv::Cold);
318 }
Aditya Kumar801394a2018-09-07 15:03:49 +0000319 CI->setIsNoInline();
320 LLVM_DEBUG(llvm::dbgs() << "Outlined Region at block: " << Region.front());
321 return OutF;
322 }
323
324 ORE.emit([&]() {
325 return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
326 &*Region[0]->begin())
327 << "Failed to extract region at block "
328 << ore::NV("Block", Region.front());
329 });
330 return nullptr;
331}
332
333// Return the function created after outlining, nullptr otherwise.
334Function *HotColdSplitting::outlineColdBlocks(Function &F,
Sebastian Pop12171602018-09-14 20:36:10 +0000335 const DenseSetBB &HotBlocks,
Aditya Kumar801394a2018-09-07 15:03:49 +0000336 DominatorTree *DT,
337 PostDomTree *PDT) {
338 auto BFI = GetBFI(F);
339 auto &ORE = (*GetORE)(F);
340 // Walking the dominator tree allows us to find the largest
341 // cold region.
342 BasicBlock *Begin = DT->getRootNode()->getBlock();
343 for (auto I = df_begin(Begin), E = df_end(Begin); I != E; ++I) {
344 BasicBlock *BB = *I;
Sebastian Pop12171602018-09-14 20:36:10 +0000345 if (PSI->isColdBB(BB, BFI) || !HotBlocks.count(BB)) {
Aditya Kumar801394a2018-09-07 15:03:49 +0000346 SmallVector<BasicBlock *, 4> ValidColdRegion, Region;
347 auto *BBNode = (*PDT)[BB];
348 auto Exit = BBNode->getIDom()->getBlock();
349 // We might need a virtual exit which post-dominates all basic blocks.
350 if (!Exit)
351 continue;
352 BasicBlock *ExitColdRegion = nullptr;
353 // Estimated cold region between a BB and its dom-frontier.
354 while (isSingleEntrySingleExit(BB, Exit, DT, PDT, Region) &&
355 isOutlineCandidate(Region, Exit)) {
356 ExitColdRegion = Exit;
357 ValidColdRegion = Region;
358 Region.clear();
359 // Update Exit recursively to its dom-frontier.
360 Exit = (*PDT)[Exit]->getIDom()->getBlock();
361 }
362 if (ExitColdRegion) {
363 ++NumColdSESEFound;
364 // Candidate for outlining. FIXME: Continue outlining.
365 // FIXME: Shouldn't need uniquing, debug isSingleEntrySingleExit
366 //std::sort(ValidColdRegion.begin(), ValidColdRegion.end());
367 auto last = std::unique(ValidColdRegion.begin(), ValidColdRegion.end());
368 ValidColdRegion.erase(last, ValidColdRegion.end());
369 return extractColdRegion(ValidColdRegion, DT, BFI, ORE);
370 }
371 }
372 }
373 return nullptr;
374}
375
376bool HotColdSplitting::run(Module &M) {
377 for (auto &F : M) {
378 if (!shouldOutlineFrom(F))
379 continue;
380 DominatorTree DT(F);
381 PostDomTree PDT(F);
382 PDT.recalculate(F);
383 DenseSetBB HotBlocks;
384 if (EnableStaticAnalyis) // Static analysis of cold blocks.
385 HotBlocks = getHotBlocks(F);
386
387 auto Outlined = outlineColdBlocks(F, HotBlocks, &DT, &PDT);
388 if (Outlined)
389 OutlinedFunctions.insert(Outlined);
390 }
391 return true;
392}
393
394bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
395 if (skipModule(M))
396 return false;
397 ProfileSummaryInfo *PSI =
398 getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000399 auto GTTI = [this](Function &F) -> TargetTransformInfo & {
400 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
401 };
Aditya Kumar801394a2018-09-07 15:03:49 +0000402 auto GBFI = [this](Function &F) {
403 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI();
404 };
405 std::unique_ptr<OptimizationRemarkEmitter> ORE;
406 std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
407 [&ORE](Function &F) -> OptimizationRemarkEmitter & {
408 ORE.reset(new OptimizationRemarkEmitter(&F));
409 return *ORE.get();
410 };
411
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000412 return HotColdSplitting(PSI, GBFI, GTTI, &GetORE).run(M);
Aditya Kumar801394a2018-09-07 15:03:49 +0000413}
414
415char HotColdSplittingLegacyPass::ID = 0;
416INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
417 "Hot Cold Splitting", false, false)
418INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
419INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
420INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
421 "Hot Cold Splitting", false, false)
422
423ModulePass *llvm::createHotColdSplittingPass() {
424 return new HotColdSplittingLegacyPass();
425}