blob: d0f3fdf0c6035b8817853d8a6abbca5438e4eb17 [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
Vedant Kumar03aaa3e2018-12-07 20:23:52 +000016#include "llvm/ADT/PostOrderIterator.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000017#include "llvm/ADT/SmallVector.h"
18#include "llvm/ADT/Statistic.h"
19#include "llvm/Analysis/AliasAnalysis.h"
20#include "llvm/Analysis/BlockFrequencyInfo.h"
21#include "llvm/Analysis/BranchProbabilityInfo.h"
22#include "llvm/Analysis/CFG.h"
23#include "llvm/Analysis/OptimizationRemarkEmitter.h"
24#include "llvm/Analysis/PostDominators.h"
25#include "llvm/Analysis/ProfileSummaryInfo.h"
Sebastian Popa1f20fc2018-09-10 15:08:02 +000026#include "llvm/Analysis/TargetTransformInfo.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000027#include "llvm/IR/BasicBlock.h"
28#include "llvm/IR/CFG.h"
Vedant Kumar03f9f152018-12-07 20:24:04 +000029#include "llvm/IR/CallSite.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000030#include "llvm/IR/DataLayout.h"
31#include "llvm/IR/DiagnosticInfo.h"
32#include "llvm/IR/Dominators.h"
33#include "llvm/IR/Function.h"
34#include "llvm/IR/Instruction.h"
35#include "llvm/IR/Instructions.h"
Vedant Kumardd4be532018-10-29 19:15:39 +000036#include "llvm/IR/IntrinsicInst.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000037#include "llvm/IR/Metadata.h"
38#include "llvm/IR/Module.h"
39#include "llvm/IR/PassManager.h"
40#include "llvm/IR/Type.h"
41#include "llvm/IR/Use.h"
42#include "llvm/IR/User.h"
43#include "llvm/IR/Value.h"
44#include "llvm/Pass.h"
45#include "llvm/Support/BlockFrequency.h"
46#include "llvm/Support/BranchProbability.h"
47#include "llvm/Support/Debug.h"
48#include "llvm/Support/raw_ostream.h"
49#include "llvm/Transforms/IPO.h"
Aditya Kumar9e20ade2018-10-03 05:55:20 +000050#include "llvm/Transforms/IPO/HotColdSplitting.h"
Aditya Kumar801394a2018-09-07 15:03:49 +000051#include "llvm/Transforms/Scalar.h"
52#include "llvm/Transforms/Utils/BasicBlockUtils.h"
53#include "llvm/Transforms/Utils/Cloning.h"
54#include "llvm/Transforms/Utils/CodeExtractor.h"
55#include "llvm/Transforms/Utils/Local.h"
56#include "llvm/Transforms/Utils/SSAUpdater.h"
57#include "llvm/Transforms/Utils/ValueMapper.h"
58#include <algorithm>
59#include <cassert>
60
61#define DEBUG_TYPE "hotcoldsplit"
62
Vedant Kumarc2990062018-10-24 22:15:41 +000063STATISTIC(NumColdRegionsFound, "Number of cold regions found.");
64STATISTIC(NumColdRegionsOutlined, "Number of cold regions outlined.");
Aditya Kumar801394a2018-09-07 15:03:49 +000065
66using namespace llvm;
67
68static cl::opt<bool> EnableStaticAnalyis("hot-cold-static-analysis",
69 cl::init(true), cl::Hidden);
70
Vedant Kumard2a895a2018-11-04 23:11:57 +000071static cl::opt<int>
Vedant Kumar32a014d2019-01-17 21:29:34 +000072 SplittingThreshold("hotcoldsplit-threshold", cl::init(3), cl::Hidden,
73 cl::desc("Code size threshold for splitting cold code "
74 "(as a multiple of TCC_Basic)"));
Aditya Kumar801394a2018-09-07 15:03:49 +000075
76namespace {
77
78struct PostDomTree : PostDomTreeBase<BasicBlock> {
79 PostDomTree(Function &F) { recalculate(F); }
80};
81
Vedant Kumarc2990062018-10-24 22:15:41 +000082/// A sequence of basic blocks.
83///
84/// A 0-sized SmallVector is slightly cheaper to move than a std::vector.
85using BlockSequence = SmallVector<BasicBlock *, 0>;
Aditya Kumar801394a2018-09-07 15:03:49 +000086
Sebastian Pop542e5222018-10-15 21:43:11 +000087// Same as blockEndsInUnreachable in CodeGen/BranchFolding.cpp. Do not modify
88// this function unless you modify the MBB version as well.
89//
90/// A no successor, non-return block probably ends in unreachable and is cold.
91/// Also consider a block that ends in an indirect branch to be a return block,
92/// since many targets use plain indirect branches to return.
Aditya Kumar801394a2018-09-07 15:03:49 +000093bool blockEndsInUnreachable(const BasicBlock &BB) {
Sebastian Pop542e5222018-10-15 21:43:11 +000094 if (!succ_empty(&BB))
95 return false;
Aditya Kumar801394a2018-09-07 15:03:49 +000096 if (BB.empty())
97 return true;
Chandler Carruthedb12a82018-10-15 10:04:59 +000098 const Instruction *I = BB.getTerminator();
Sebastian Pop542e5222018-10-15 21:43:11 +000099 return !(isa<ReturnInst>(I) || isa<IndirectBrInst>(I));
Aditya Kumar801394a2018-09-07 15:03:49 +0000100}
101
Vedant Kumar03f9f152018-12-07 20:24:04 +0000102bool unlikelyExecuted(BasicBlock &BB) {
Aditya Kumar801394a2018-09-07 15:03:49 +0000103 // Exception handling blocks are unlikely executed.
104 if (BB.isEHPad())
105 return true;
Vedant Kumar03f9f152018-12-07 20:24:04 +0000106
107 // The block is cold if it calls/invokes a cold function.
108 for (Instruction &I : BB)
109 if (auto CS = CallSite(&I))
110 if (CS.hasFnAttr(Attribute::Cold))
Aditya Kumar801394a2018-09-07 15:03:49 +0000111 return true;
112
Vedant Kumar03f9f152018-12-07 20:24:04 +0000113 // The block is cold if it has an unreachable terminator, unless it's
114 // preceded by a call to a (possibly warm) noreturn call (e.g. longjmp).
115 if (blockEndsInUnreachable(BB)) {
116 if (auto *CI =
117 dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
118 if (CI->hasFnAttr(Attribute::NoReturn))
Aditya Kumar801394a2018-09-07 15:03:49 +0000119 return false;
Vedant Kumar03f9f152018-12-07 20:24:04 +0000120 return true;
121 }
122
Aditya Kumar801394a2018-09-07 15:03:49 +0000123 return false;
124}
125
Vedant Kumarc2990062018-10-24 22:15:41 +0000126/// Check whether it's safe to outline \p BB.
127static bool mayExtractBlock(const BasicBlock &BB) {
Vedant Kumarb3a7cae2018-12-11 18:05:31 +0000128 return !BB.hasAddressTaken() && !BB.isEHPad();
Sebastian Pop542e5222018-10-15 21:43:11 +0000129}
130
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000131/// Check whether \p Region is profitable to outline.
132static bool isProfitableToOutline(const BlockSequence &Region,
Vedant Kumard2a895a2018-11-04 23:11:57 +0000133 TargetTransformInfo &TTI) {
Vedant Kumar32a014d2019-01-17 21:29:34 +0000134 // If the splitting threshold is set at or below zero, skip the usual
135 // profitability check.
136 if (SplittingThreshold <= 0)
137 return true;
138
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000139 if (Region.size() > 1)
140 return true;
141
Vedant Kumard2a895a2018-11-04 23:11:57 +0000142 int Cost = 0;
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000143 const BasicBlock &BB = *Region[0];
Vedant Kumardd4be532018-10-29 19:15:39 +0000144 for (const Instruction &I : BB) {
145 if (isa<DbgInfoIntrinsic>(&I) || &I == BB.getTerminator())
146 continue;
Vedant Kumard2a895a2018-11-04 23:11:57 +0000147
148 Cost += TTI.getInstructionCost(&I, TargetTransformInfo::TCK_CodeSize);
149
Vedant Kumar32a014d2019-01-17 21:29:34 +0000150 if (Cost >= (SplittingThreshold * TargetTransformInfo::TCC_Basic))
Vedant Kumardd4be532018-10-29 19:15:39 +0000151 return true;
152 }
153 return false;
154}
155
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000156/// Mark \p F cold. Return true if it's changed.
157static bool markEntireFunctionCold(Function &F) {
158 assert(!F.hasFnAttribute(Attribute::OptimizeNone) && "Can't mark this cold");
159 bool Changed = false;
160 if (!F.hasFnAttribute(Attribute::MinSize)) {
161 F.addFnAttr(Attribute::MinSize);
162 Changed = true;
Aditya Kumar801394a2018-09-07 15:03:49 +0000163 }
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000164 // TODO: Move this function into a cold section.
165 return Changed;
Aditya Kumar801394a2018-09-07 15:03:49 +0000166}
167
168class HotColdSplitting {
169public:
170 HotColdSplitting(ProfileSummaryInfo *ProfSI,
171 function_ref<BlockFrequencyInfo *(Function &)> GBFI,
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000172 function_ref<TargetTransformInfo &(Function &)> GTTI,
Aditya Kumar801394a2018-09-07 15:03:49 +0000173 std::function<OptimizationRemarkEmitter &(Function &)> *GORE)
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000174 : PSI(ProfSI), GetBFI(GBFI), GetTTI(GTTI), GetORE(GORE) {}
Aditya Kumar801394a2018-09-07 15:03:49 +0000175 bool run(Module &M);
176
177private:
178 bool shouldOutlineFrom(const Function &F) const;
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000179 bool outlineColdRegions(Function &F, ProfileSummaryInfo &PSI,
180 BlockFrequencyInfo *BFI, TargetTransformInfo &TTI,
181 DominatorTree &DT, PostDomTree &PDT,
182 OptimizationRemarkEmitter &ORE);
Vedant Kumarc2990062018-10-24 22:15:41 +0000183 Function *extractColdRegion(const BlockSequence &Region, DominatorTree &DT,
Vedant Kumard2a895a2018-11-04 23:11:57 +0000184 BlockFrequencyInfo *BFI, TargetTransformInfo &TTI,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000185 OptimizationRemarkEmitter &ORE, unsigned Count);
Aditya Kumar801394a2018-09-07 15:03:49 +0000186 SmallPtrSet<const Function *, 2> OutlinedFunctions;
187 ProfileSummaryInfo *PSI;
188 function_ref<BlockFrequencyInfo *(Function &)> GetBFI;
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000189 function_ref<TargetTransformInfo &(Function &)> GetTTI;
Aditya Kumar801394a2018-09-07 15:03:49 +0000190 std::function<OptimizationRemarkEmitter &(Function &)> *GetORE;
191};
192
193class HotColdSplittingLegacyPass : public ModulePass {
194public:
195 static char ID;
196 HotColdSplittingLegacyPass() : ModulePass(ID) {
197 initializeHotColdSplittingLegacyPassPass(*PassRegistry::getPassRegistry());
198 }
199
200 void getAnalysisUsage(AnalysisUsage &AU) const override {
201 AU.addRequired<AssumptionCacheTracker>();
202 AU.addRequired<BlockFrequencyInfoWrapperPass>();
203 AU.addRequired<ProfileSummaryInfoWrapperPass>();
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000204 AU.addRequired<TargetTransformInfoWrapperPass>();
Aditya Kumar801394a2018-09-07 15:03:49 +0000205 }
206
207 bool runOnModule(Module &M) override;
208};
209
210} // end anonymous namespace
211
212// Returns false if the function should not be considered for hot-cold split
Sebastian Pop0f30f082018-09-14 20:36:19 +0000213// optimization.
Aditya Kumar801394a2018-09-07 15:03:49 +0000214bool HotColdSplitting::shouldOutlineFrom(const Function &F) const {
Sebastian Pop0f30f082018-09-14 20:36:19 +0000215 // Do not try to outline again from an already outlined cold function.
216 if (OutlinedFunctions.count(&F))
217 return false;
218
Aditya Kumar801394a2018-09-07 15:03:49 +0000219 if (F.size() <= 2)
220 return false;
221
Vedant Kumarc2990062018-10-24 22:15:41 +0000222 // TODO: Consider only skipping functions marked `optnone` or `cold`.
223
Aditya Kumar801394a2018-09-07 15:03:49 +0000224 if (F.hasAddressTaken())
225 return false;
226
227 if (F.hasFnAttribute(Attribute::AlwaysInline))
228 return false;
229
230 if (F.hasFnAttribute(Attribute::NoInline))
231 return false;
232
233 if (F.getCallingConv() == CallingConv::Cold)
234 return false;
235
236 if (PSI->isFunctionEntryCold(&F))
237 return false;
238 return true;
239}
240
Vedant Kumarc2990062018-10-24 22:15:41 +0000241Function *HotColdSplitting::extractColdRegion(const BlockSequence &Region,
242 DominatorTree &DT,
243 BlockFrequencyInfo *BFI,
Vedant Kumard2a895a2018-11-04 23:11:57 +0000244 TargetTransformInfo &TTI,
Vedant Kumarc2990062018-10-24 22:15:41 +0000245 OptimizationRemarkEmitter &ORE,
246 unsigned Count) {
Teresa Johnsonf431a2f2018-10-22 19:06:42 +0000247 assert(!Region.empty());
Sebastian Pop12171602018-09-14 20:36:10 +0000248
Aditya Kumar801394a2018-09-07 15:03:49 +0000249 // TODO: Pass BFI and BPI to update profile information.
Vedant Kumarc2990062018-10-24 22:15:41 +0000250 CodeExtractor CE(Region, &DT, /* AggregateArgs */ false, /* BFI */ nullptr,
Teresa Johnsonc8dba682018-10-24 18:53:47 +0000251 /* BPI */ nullptr, /* AllowVarArgs */ false,
252 /* AllowAlloca */ false,
253 /* Suffix */ "cold." + std::to_string(Count));
Aditya Kumar801394a2018-09-07 15:03:49 +0000254
255 SetVector<Value *> Inputs, Outputs, Sinks;
256 CE.findInputsOutputs(Inputs, Outputs, Sinks);
257
258 // Do not extract regions that have live exit variables.
Vedant Kumarc2990062018-10-24 22:15:41 +0000259 if (Outputs.size() > 0) {
260 LLVM_DEBUG(llvm::dbgs() << "Not outlining; live outputs\n");
Aditya Kumar801394a2018-09-07 15:03:49 +0000261 return nullptr;
Vedant Kumarc2990062018-10-24 22:15:41 +0000262 }
Aditya Kumar801394a2018-09-07 15:03:49 +0000263
Vedant Kumarc2990062018-10-24 22:15:41 +0000264 // TODO: Run MergeBasicBlockIntoOnlyPred on the outlined function.
Teresa Johnsonf431a2f2018-10-22 19:06:42 +0000265 Function *OrigF = Region[0]->getParent();
Aditya Kumar801394a2018-09-07 15:03:49 +0000266 if (Function *OutF = CE.extractCodeRegion()) {
267 User *U = *OutF->user_begin();
268 CallInst *CI = cast<CallInst>(U);
269 CallSite CS(CI);
Vedant Kumarc2990062018-10-24 22:15:41 +0000270 NumColdRegionsOutlined++;
Vedant Kumard2a895a2018-11-04 23:11:57 +0000271 if (TTI.useColdCCForColdCall(*OutF)) {
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000272 OutF->setCallingConv(CallingConv::Cold);
273 CS.setCallingConv(CallingConv::Cold);
274 }
Aditya Kumar801394a2018-09-07 15:03:49 +0000275 CI->setIsNoInline();
Vedant Kumar50315462018-10-23 19:41:12 +0000276
277 // Try to make the outlined code as small as possible on the assumption
278 // that it's cold.
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000279 markEntireFunctionCold(*OutF);
Vedant Kumar50315462018-10-23 19:41:12 +0000280
Sebastian Pop0f30f082018-09-14 20:36:19 +0000281 LLVM_DEBUG(llvm::dbgs() << "Outlined Region: " << *OutF);
Teresa Johnsonf431a2f2018-10-22 19:06:42 +0000282 ORE.emit([&]() {
283 return OptimizationRemark(DEBUG_TYPE, "HotColdSplit",
284 &*Region[0]->begin())
285 << ore::NV("Original", OrigF) << " split cold code into "
286 << ore::NV("Split", OutF);
287 });
Aditya Kumar801394a2018-09-07 15:03:49 +0000288 return OutF;
289 }
290
291 ORE.emit([&]() {
292 return OptimizationRemarkMissed(DEBUG_TYPE, "ExtractFailed",
293 &*Region[0]->begin())
294 << "Failed to extract region at block "
295 << ore::NV("Block", Region.front());
296 });
297 return nullptr;
298}
299
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000300/// A pair of (basic block, score).
301using BlockTy = std::pair<BasicBlock *, unsigned>;
302
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000303namespace {
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000304/// A maximal outlining region. This contains all blocks post-dominated by a
305/// sink block, the sink block itself, and all blocks dominated by the sink.
306class OutliningRegion {
307 /// A list of (block, score) pairs. A block's score is non-zero iff it's a
308 /// viable sub-region entry point. Blocks with higher scores are better entry
309 /// points (i.e. they are more distant ancestors of the sink block).
310 SmallVector<BlockTy, 0> Blocks = {};
311
312 /// The suggested entry point into the region. If the region has multiple
313 /// entry points, all blocks within the region may not be reachable from this
314 /// entry point.
315 BasicBlock *SuggestedEntryPoint = nullptr;
316
317 /// Whether the entire function is cold.
318 bool EntireFunctionCold = false;
319
320 /// Whether or not \p BB could be the entry point of an extracted region.
321 static bool isViableEntryPoint(BasicBlock &BB) { return !BB.isEHPad(); }
322
323 /// If \p BB is a viable entry point, return \p Score. Return 0 otherwise.
324 static unsigned getEntryPointScore(BasicBlock &BB, unsigned Score) {
325 return isViableEntryPoint(BB) ? Score : 0;
326 }
327
328 /// These scores should be lower than the score for predecessor blocks,
329 /// because regions starting at predecessor blocks are typically larger.
330 static constexpr unsigned ScoreForSuccBlock = 1;
331 static constexpr unsigned ScoreForSinkBlock = 1;
332
333 OutliningRegion(const OutliningRegion &) = delete;
334 OutliningRegion &operator=(const OutliningRegion &) = delete;
335
336public:
337 OutliningRegion() = default;
338 OutliningRegion(OutliningRegion &&) = default;
339 OutliningRegion &operator=(OutliningRegion &&) = default;
340
341 static OutliningRegion create(BasicBlock &SinkBB, const DominatorTree &DT,
342 const PostDomTree &PDT) {
343 OutliningRegion ColdRegion;
344
345 SmallPtrSet<BasicBlock *, 4> RegionBlocks;
346
347 auto addBlockToRegion = [&](BasicBlock *BB, unsigned Score) {
348 RegionBlocks.insert(BB);
349 ColdRegion.Blocks.emplace_back(BB, Score);
350 assert(RegionBlocks.size() == ColdRegion.Blocks.size() && "Duplicate BB");
351 };
352
353 // The ancestor farthest-away from SinkBB, and also post-dominated by it.
354 unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
355 ColdRegion.SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB : nullptr;
356 unsigned BestScore = SinkScore;
357
358 // Visit SinkBB's ancestors using inverse DFS.
359 auto PredIt = ++idf_begin(&SinkBB);
360 auto PredEnd = idf_end(&SinkBB);
361 while (PredIt != PredEnd) {
362 BasicBlock &PredBB = **PredIt;
363 bool SinkPostDom = PDT.dominates(&SinkBB, &PredBB);
364
365 // If the predecessor is cold and has no predecessors, the entire
366 // function must be cold.
367 if (SinkPostDom && pred_empty(&PredBB)) {
368 ColdRegion.EntireFunctionCold = true;
369 return ColdRegion;
370 }
371
372 // If SinkBB does not post-dominate a predecessor, do not mark the
373 // predecessor (or any of its predecessors) cold.
374 if (!SinkPostDom || !mayExtractBlock(PredBB)) {
375 PredIt.skipChildren();
376 continue;
377 }
378
379 // Keep track of the post-dominated ancestor farthest away from the sink.
380 // The path length is always >= 2, ensuring that predecessor blocks are
381 // considered as entry points before the sink block.
382 unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
383 if (PredScore > BestScore) {
384 ColdRegion.SuggestedEntryPoint = &PredBB;
385 BestScore = PredScore;
386 }
387
388 addBlockToRegion(&PredBB, PredScore);
389 ++PredIt;
Vedant Kumarc2990062018-10-24 22:15:41 +0000390 }
391
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000392 // Add SinkBB to the cold region. It's considered as an entry point before
393 // any sink-successor blocks.
394 addBlockToRegion(&SinkBB, SinkScore);
395
396 // Find all successors of SinkBB dominated by SinkBB using DFS.
397 auto SuccIt = ++df_begin(&SinkBB);
398 auto SuccEnd = df_end(&SinkBB);
399 while (SuccIt != SuccEnd) {
400 BasicBlock &SuccBB = **SuccIt;
401 bool SinkDom = DT.dominates(&SinkBB, &SuccBB);
402
403 // Don't allow the backwards & forwards DFSes to mark the same block.
404 bool DuplicateBlock = RegionBlocks.count(&SuccBB);
405
406 // If SinkBB does not dominate a successor, do not mark the successor (or
407 // any of its successors) cold.
408 if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
409 SuccIt.skipChildren();
410 continue;
411 }
412
413 unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
414 if (SuccScore > BestScore) {
415 ColdRegion.SuggestedEntryPoint = &SuccBB;
416 BestScore = SuccScore;
417 }
418
419 addBlockToRegion(&SuccBB, SuccScore);
420 ++SuccIt;
421 }
422
423 return ColdRegion;
424 }
425
426 /// Whether this region has nothing to extract.
427 bool empty() const { return !SuggestedEntryPoint; }
428
429 /// The blocks in this region.
430 ArrayRef<std::pair<BasicBlock *, unsigned>> blocks() const { return Blocks; }
431
432 /// Whether the entire function containing this region is cold.
433 bool isEntireFunctionCold() const { return EntireFunctionCold; }
434
435 /// Remove a sub-region from this region and return it as a block sequence.
436 BlockSequence takeSingleEntrySubRegion(DominatorTree &DT) {
437 assert(!empty() && !isEntireFunctionCold() && "Nothing to extract");
438
439 // Remove blocks dominated by the suggested entry point from this region.
440 // During the removal, identify the next best entry point into the region.
441 // Ensure that the first extracted block is the suggested entry point.
442 BlockSequence SubRegion = {SuggestedEntryPoint};
443 BasicBlock *NextEntryPoint = nullptr;
444 unsigned NextScore = 0;
445 auto RegionEndIt = Blocks.end();
446 auto RegionStartIt = remove_if(Blocks, [&](const BlockTy &Block) {
447 BasicBlock *BB = Block.first;
448 unsigned Score = Block.second;
449 bool InSubRegion =
450 BB == SuggestedEntryPoint || DT.dominates(SuggestedEntryPoint, BB);
451 if (!InSubRegion && Score > NextScore) {
452 NextEntryPoint = BB;
453 NextScore = Score;
454 }
455 if (InSubRegion && BB != SuggestedEntryPoint)
456 SubRegion.push_back(BB);
457 return InSubRegion;
458 });
459 Blocks.erase(RegionStartIt, RegionEndIt);
460
461 // Update the suggested entry point.
462 SuggestedEntryPoint = NextEntryPoint;
463
464 return SubRegion;
465 }
466};
Benjamin Kramerb17d2132019-01-12 18:36:22 +0000467} // namespace
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000468
469bool HotColdSplitting::outlineColdRegions(Function &F, ProfileSummaryInfo &PSI,
470 BlockFrequencyInfo *BFI,
471 TargetTransformInfo &TTI,
472 DominatorTree &DT, PostDomTree &PDT,
473 OptimizationRemarkEmitter &ORE) {
474 bool Changed = false;
475
476 // The set of cold blocks.
477 SmallPtrSet<BasicBlock *, 4> ColdBlocks;
478
479 // The worklist of non-intersecting regions left to outline.
480 SmallVector<OutliningRegion, 2> OutliningWorklist;
481
482 // Set up an RPO traversal. Experimentally, this performs better (outlines
483 // more) than a PO traversal, because we prevent region overlap by keeping
484 // the first region to contain a block.
485 ReversePostOrderTraversal<Function *> RPOT(&F);
486
487 // Find all cold regions.
488 for (BasicBlock *BB : RPOT) {
489 // Skip blocks which can't be outlined.
490 if (!mayExtractBlock(*BB))
491 continue;
492
493 // This block is already part of some outlining region.
494 if (ColdBlocks.count(BB))
495 continue;
496
497 bool Cold = PSI.isColdBlock(BB, BFI) ||
498 (EnableStaticAnalyis && unlikelyExecuted(*BB));
499 if (!Cold)
500 continue;
501
502 LLVM_DEBUG({
503 dbgs() << "Found a cold block:\n";
504 BB->dump();
505 });
506
507 auto Region = OutliningRegion::create(*BB, DT, PDT);
508 if (Region.empty())
509 continue;
510
511 if (Region.isEntireFunctionCold()) {
512 LLVM_DEBUG(dbgs() << "Entire function is cold\n");
513 return markEntireFunctionCold(F);
514 }
515
516 // If this outlining region intersects with another, drop the new region.
517 //
518 // TODO: It's theoretically possible to outline more by only keeping the
519 // largest region which contains a block, but the extra bookkeeping to do
520 // this is tricky/expensive.
521 bool RegionsOverlap = any_of(Region.blocks(), [&](const BlockTy &Block) {
522 return !ColdBlocks.insert(Block.first).second;
523 });
524 if (RegionsOverlap)
525 continue;
526
527 OutliningWorklist.emplace_back(std::move(Region));
528 ++NumColdRegionsFound;
529 }
530
531 // Outline single-entry cold regions, splitting up larger regions as needed.
532 unsigned OutlinedFunctionID = 1;
533 while (!OutliningWorklist.empty()) {
534 OutliningRegion Region = OutliningWorklist.pop_back_val();
535 assert(!Region.empty() && "Empty outlining region in worklist");
536 do {
537 BlockSequence SubRegion = Region.takeSingleEntrySubRegion(DT);
538 if (!isProfitableToOutline(SubRegion, TTI)) {
539 LLVM_DEBUG({
540 dbgs() << "Skipping outlining; not profitable to outline\n";
541 SubRegion[0]->dump();
542 });
543 continue;
544 }
545
546 LLVM_DEBUG({
547 dbgs() << "Hot/cold splitting attempting to outline these blocks:\n";
548 for (BasicBlock *BB : SubRegion)
549 BB->dump();
550 });
551
552 Function *Outlined =
553 extractColdRegion(SubRegion, DT, BFI, TTI, ORE, OutlinedFunctionID);
554 if (Outlined) {
555 ++OutlinedFunctionID;
556 OutlinedFunctions.insert(Outlined);
557 Changed = true;
558 }
559 } while (!Region.empty());
560 }
561
562 return Changed;
563}
564
565bool HotColdSplitting::run(Module &M) {
566 bool Changed = false;
567 OutlinedFunctions.clear();
568 for (auto &F : M) {
569 if (!shouldOutlineFrom(F)) {
570 LLVM_DEBUG(llvm::dbgs() << "Skipping " << F.getName() << "\n");
571 continue;
572 }
Vedant Kumarc2990062018-10-24 22:15:41 +0000573 LLVM_DEBUG(llvm::dbgs() << "Outlining in " << F.getName() << "\n");
Aditya Kumar801394a2018-09-07 15:03:49 +0000574 DominatorTree DT(F);
575 PostDomTree PDT(F);
576 PDT.recalculate(F);
Vedant Kumarc2990062018-10-24 22:15:41 +0000577 BlockFrequencyInfo *BFI = GetBFI(F);
Vedant Kumard2a895a2018-11-04 23:11:57 +0000578 TargetTransformInfo &TTI = GetTTI(F);
Vedant Kumarc2990062018-10-24 22:15:41 +0000579 OptimizationRemarkEmitter &ORE = (*GetORE)(F);
Vedant Kumar03aaa3e2018-12-07 20:23:52 +0000580 Changed |= outlineColdRegions(F, *PSI, BFI, TTI, DT, PDT, ORE);
Aditya Kumar801394a2018-09-07 15:03:49 +0000581 }
Vedant Kumarc2990062018-10-24 22:15:41 +0000582 return Changed;
Aditya Kumar801394a2018-09-07 15:03:49 +0000583}
584
585bool HotColdSplittingLegacyPass::runOnModule(Module &M) {
586 if (skipModule(M))
587 return false;
588 ProfileSummaryInfo *PSI =
Vedant Kumare7b789b2018-11-19 05:23:16 +0000589 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000590 auto GTTI = [this](Function &F) -> TargetTransformInfo & {
591 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
592 };
Aditya Kumar801394a2018-09-07 15:03:49 +0000593 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
Sebastian Popa1f20fc2018-09-10 15:08:02 +0000603 return HotColdSplitting(PSI, GBFI, GTTI, &GetORE).run(M);
Aditya Kumar801394a2018-09-07 15:03:49 +0000604}
605
Aditya Kumar9e20ade2018-10-03 05:55:20 +0000606PreservedAnalyses
607HotColdSplittingPass::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
Aditya Kumar801394a2018-09-07 15:03:49 +0000638char HotColdSplittingLegacyPass::ID = 0;
639INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit",
640 "Hot Cold Splitting", false, false)
641INITIALIZE_PASS_DEPENDENCY(ProfileSummaryInfoWrapperPass)
642INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)
643INITIALIZE_PASS_END(HotColdSplittingLegacyPass, "hotcoldsplit",
644 "Hot Cold Splitting", false, false)
645
646ModulePass *llvm::createHotColdSplittingPass() {
647 return new HotColdSplittingLegacyPass();
648}