74 #define DEBUG_TYPE "hotcoldsplit" 76 STATISTIC(NumColdRegionsFound,
"Number of cold regions found.");
77 STATISTIC(NumColdRegionsOutlined,
"Number of cold regions outlined.");
86 cl::desc(
"Base penalty for splitting cold code (as a " 87 "multiple of TCC_Basic)"));
102 return !(isa<ReturnInst>(
I) || isa<IndirectBrInst>(I));
121 dyn_cast_or_null<CallInst>(BB.getTerminator()->getPrevNode()))
122 if (CI->hasFnAttr(Attribute::NoReturn))
131 static bool mayExtractBlock(
const BasicBlock &BB) {
140 !isa<ResumeInst>(Term);
147 static bool markFunctionCold(
Function &
F,
bool UpdateEntryCount =
false) {
149 bool Changed =
false;
158 if (UpdateEntryCount) {
168 class HotColdSplittingLegacyPass :
public ModulePass {
171 HotColdSplittingLegacyPass() :
ModulePass(ID) {
182 bool runOnModule(
Module &M)
override;
188 bool HotColdSplitting::isFunctionCold(
const Function &F)
const {
195 if (PSI->isFunctionEntryCold(&F))
203 bool HotColdSplitting::shouldOutlineFrom(
const Function &F)
const {
241 unsigned NumInputs,
unsigned NumOutputs) {
243 LLVM_DEBUG(
dbgs() <<
"Applying penalty for splitting: " << Penalty <<
"\n");
252 LLVM_DEBUG(
dbgs() <<
"Applying penalty for: " << NumInputs <<
" inputs\n");
254 Penalty += CostForArgMaterialization * NumInputs;
258 LLVM_DEBUG(
dbgs() <<
"Applying penalty for: " << NumOutputs <<
" outputs\n");
260 Penalty += CostForRegionOutput * NumOutputs;
264 bool NoBlocksReturn =
true;
275 if (
find(Region, SuccBB) == Region.end()) {
276 NoBlocksReturn =
false;
277 SuccsOutsideRegion.
insert(SuccBB);
283 if (NoBlocksReturn) {
285 <<
" non-returning terminators\n");
286 Penalty -= Region.size();
291 if (!SuccsOutsideRegion.
empty()) {
293 <<
" non-region successors\n");
300 Function *HotColdSplitting::extractColdRegion(
315 CE.findInputsOutputs(Inputs, Outputs, Sinks);
317 int OutliningPenalty =
319 LLVM_DEBUG(
dbgs() <<
"Split profitability: benefit = " << OutliningBenefit
320 <<
", penalty = " << OutliningPenalty <<
"\n");
321 if (OutliningBenefit <= OutliningPenalty)
324 Function *OrigF = Region[0]->getParent();
325 if (
Function *OutF = CE.extractCodeRegion(CEAC)) {
329 NumColdRegionsOutlined++;
339 markFunctionCold(*OutF, BFI !=
nullptr);
344 &*Region[0]->
begin())
345 <<
ore::NV(
"Original", OrigF) <<
" split cold code into " 353 &*Region[0]->
begin())
354 <<
"Failed to extract region at block " 361 using BlockTy = std::pair<BasicBlock *, unsigned>;
368 class OutliningRegion {
380 bool EntireFunctionCold =
false;
383 static unsigned getEntryPointScore(
BasicBlock &BB,
unsigned Score) {
384 return mayExtractBlock(BB) ? Score : 0;
389 static constexpr
unsigned ScoreForSuccBlock = 1;
390 static constexpr
unsigned ScoreForSinkBlock = 1;
392 OutliningRegion(
const OutliningRegion &) =
delete;
393 OutliningRegion &operator=(
const OutliningRegion &) =
delete;
396 OutliningRegion() =
default;
397 OutliningRegion(OutliningRegion &&) =
default;
398 OutliningRegion &operator=(OutliningRegion &&) =
default;
400 static std::vector<OutliningRegion> create(
BasicBlock &SinkBB,
403 std::vector<OutliningRegion> Regions;
406 Regions.emplace_back();
407 OutliningRegion *ColdRegion = &Regions.back();
409 auto addBlockToRegion = [&](
BasicBlock *BB,
unsigned Score) {
411 ColdRegion->Blocks.emplace_back(BB, Score);
415 unsigned SinkScore = getEntryPointScore(SinkBB, ScoreForSinkBlock);
416 ColdRegion->SuggestedEntryPoint = (SinkScore > 0) ? &SinkBB :
nullptr;
417 unsigned BestScore = SinkScore;
421 auto PredEnd =
idf_end(&SinkBB);
422 while (PredIt != PredEnd) {
424 bool SinkPostDom = PDT.
dominates(&SinkBB, &PredBB);
429 ColdRegion->EntireFunctionCold =
true;
435 if (!SinkPostDom || !mayExtractBlock(PredBB)) {
436 PredIt.skipChildren();
443 unsigned PredScore = getEntryPointScore(PredBB, PredIt.getPathLength());
444 if (PredScore > BestScore) {
445 ColdRegion->SuggestedEntryPoint = &PredBB;
446 BestScore = PredScore;
449 addBlockToRegion(&PredBB, PredScore);
459 if (mayExtractBlock(SinkBB)) {
460 addBlockToRegion(&SinkBB, SinkScore);
462 Regions.emplace_back();
463 ColdRegion = &Regions.back();
469 auto SuccEnd =
df_end(&SinkBB);
470 while (SuccIt != SuccEnd) {
472 bool SinkDom = DT.
dominates(&SinkBB, &SuccBB);
475 bool DuplicateBlock = RegionBlocks.
count(&SuccBB);
479 if (DuplicateBlock || !SinkDom || !mayExtractBlock(SuccBB)) {
480 SuccIt.skipChildren();
484 unsigned SuccScore = getEntryPointScore(SuccBB, ScoreForSuccBlock);
485 if (SuccScore > BestScore) {
486 ColdRegion->SuggestedEntryPoint = &SuccBB;
487 BestScore = SuccScore;
490 addBlockToRegion(&SuccBB, SuccScore);
498 bool empty()
const {
return !SuggestedEntryPoint; }
504 bool isEntireFunctionCold()
const {
return EntireFunctionCold; }
508 assert(!
empty() && !isEntireFunctionCold() &&
"Nothing to extract");
515 unsigned NextScore = 0;
516 auto RegionEndIt = Blocks.
end();
519 unsigned Score = Block.second;
521 BB == SuggestedEntryPoint || DT.
dominates(SuggestedEntryPoint, BB);
522 if (!InSubRegion && Score > NextScore) {
526 if (InSubRegion && BB != SuggestedEntryPoint)
530 Blocks.
erase(RegionStartIt, RegionEndIt);
533 SuggestedEntryPoint = NextEntryPoint;
540 bool HotColdSplitting::outlineColdRegions(
Function &F,
bool HasProfileSummary) {
541 bool Changed =
false;
555 std::unique_ptr<DominatorTree> DT;
556 std::unique_ptr<PostDominatorTree> PDT;
562 if (HasProfileSummary)
572 if (ColdBlocks.
count(BB))
575 bool Cold = (BFI && PSI->isColdBlock(BB, BFI)) ||
581 dbgs() <<
"Found a cold block:\n";
586 DT = std::make_unique<DominatorTree>(
F);
588 PDT = std::make_unique<PostDominatorTree>(
F);
590 auto Regions = OutliningRegion::create(*BB, *DT, *PDT);
591 for (OutliningRegion &Region : Regions) {
595 if (Region.isEntireFunctionCold()) {
597 return markFunctionCold(F);
605 bool RegionsOverlap =
any_of(Region.blocks(), [&](
const BlockTy &Block) {
606 return !ColdBlocks.
insert(Block.first).second;
612 ++NumColdRegionsFound;
616 if (OutliningWorklist.
empty())
620 unsigned OutlinedFunctionID = 1;
624 OutliningRegion Region = OutliningWorklist.
pop_back_val();
625 assert(!Region.empty() &&
"Empty outlining region in worklist");
627 BlockSequence SubRegion = Region.takeSingleEntrySubRegion(*DT);
629 dbgs() <<
"Hot/cold splitting attempting to outline these blocks:\n";
634 Function *Outlined = extractColdRegion(SubRegion, CEAC, *DT, BFI, TTI,
635 ORE, AC, OutlinedFunctionID);
637 ++OutlinedFunctionID;
640 }
while (!Region.empty());
641 }
while (!OutliningWorklist.
empty());
647 bool Changed =
false;
649 for (
auto It = M.
begin(), End = M.
end(); It != End; ++It) {
661 if (isFunctionCold(F)) {
662 Changed |= markFunctionCold(F);
666 if (!shouldOutlineFrom(F)) {
672 Changed |= outlineColdRegions(F, HasProfileSummary);
677 bool HotColdSplittingLegacyPass::runOnModule(
Module &M) {
681 &getAnalysis<ProfileSummaryInfoWrapperPass>().getPSI();
683 return this->getAnalysis<TargetTransformInfoWrapperPass>().getTTI(F);
686 return &this->getAnalysis<BlockFrequencyInfoWrapperPass>(
F).getBFI();
688 std::unique_ptr<OptimizationRemarkEmitter> ORE;
689 std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
695 if (
auto *ACT = getAnalysisIfAvailable<AssumptionCacheTracker>())
696 return ACT->lookupAssumptionCache(F);
715 std::function<TargetTransformInfo &(Function &)> GTTI =
720 std::unique_ptr<OptimizationRemarkEmitter> ORE;
721 std::function<OptimizationRemarkEmitter &(Function &)> GetORE =
736 "Hot Cold Splitting",
false,
false)
743 return new HotColdSplittingLegacyPass();
StringRef getSection() const
Get the custom section of this global if it has one.
INITIALIZE_PASS_BEGIN(HotColdSplittingLegacyPass, "hotcoldsplit", "Hot Cold Splitting", false, false) INITIALIZE_PASS_END(HotColdSplittingLegacyPass
reference emplace_back(ArgTypes &&... Args)
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
DiagnosticInfoOptimizationBase::Argument NV
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
bool hasOptNone() const
Do not optimize this function (-O0).
size_type size() const
Determine the number of elements in the SetVector.
A Module instance is used to store all the information related to an LLVM module. ...
PreservedAnalyses run(Module &M, ModuleAnalysisManager &AM)
void push_back(const T &Elt)
Analysis providing profile information.
This class represents a function call, abstracting a target machine's calling convention.
static cl::opt< bool > EnableStaticAnalyis("hot-cold-static-analysis", cl::init(true), cl::Hidden)
An immutable pass that tracks lazily created AssumptionCache objects.
Metadata * getProfileSummary(bool IsCS)
Returns profile summary metadata.
A cache of @llvm.assume calls within a function.
Analysis pass providing the TargetTransformInfo.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This defines the Use class.
void dump() const
Support for debugging, callable in GDB: V->dump()
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
void setEntryCount(ProfileCount Count, const DenseSet< GlobalValue::GUID > *Imports=nullptr)
Set the entry count for this function.
An analysis pass based on legacy pass manager to deliver ProfileSummaryInfo.
Legacy analysis pass which computes BlockFrequencyInfo.
STATISTIC(NumColdRegionsFound, "Number of cold regions found.")
static bool blockEndsInUnreachable(const MachineBasicBlock *MBB)
A no successor, non-return block probably ends in unreachable and is cold.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static PreservedAnalyses none()
Convenience factory function for the empty preserved set.
idf_iterator< T > idf_begin(const T &G)
idf_iterator< T > idf_end(const T &G)
BlockFrequencyInfo pass uses BlockFrequencyInfoImpl implementation to estimate IR basic block frequen...
initializer< Ty > init(const Ty &Val)
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
bool dominates(const Instruction *I1, const Instruction *I2) const
Return true if I1 dominates I2.
An analysis pass based on the new PM to deliver ProfileSummaryInfo.
df_iterator< T > df_end(const T &G)
iterator_range< filter_iterator< BasicBlock::const_iterator, std::function< bool(const Instruction &)> > > instructionsWithoutDebug() const
Return a const iterator range over the instructions in the block, skipping any debug instructions...
LLVM_NODISCARD bool empty() const
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Represent the analysis usage information of a pass.
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool pred_empty(const BasicBlock *BB)
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
bool succ_empty(const Instruction *I)
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
A function analysis which provides an AssumptionCache.
bool hasAddressTaken() const
Returns true if there are any uses of this basic block other than direct branches, switches, etc.
Analysis pass which computes BlockFrequencyInfo.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
std::pair< BasicBlock *, unsigned > BlockTy
A pair of (basic block, score).
void initializeHotColdSplittingLegacyPassPass(PassRegistry &)
static cl::opt< int > SplittingThreshold("hotcoldsplit-threshold", cl::init(2), cl::Hidden, cl::desc("Base penalty for splitting cold code (as a " "multiple of TCC_Basic)"))
CallingConv::ID getCallingConv() const
getCallingConv()/setCallingConv(CC) - These method get and set the calling convention of this functio...
bool hasSection() const
Check if this global has a custom object file section.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD T pop_back_val()
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static int getOutliningBenefit(ArrayRef< BasicBlock *> Region, TargetTransformInfo &TTI)
Get the benefit score of outlining Region.
df_iterator< T > df_begin(const T &G)
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
ModulePass * createHotColdSplittingPass()
createHotColdSplittingPass - This pass outlines cold blocks into a separate function(s).
LLVM_NODISCARD bool empty() const
static int getOutliningPenalty(ArrayRef< BasicBlock *> Region, unsigned NumInputs, unsigned NumOutputs)
Get the penalty score for outlining Region.
StringRef getName() const
Return a constant reference to the value's name.
ModulePass class - This class is used to implement unstructured interprocedural optimizations and ana...
const std::string to_string(const T &Value)
bool isDeclaration() const
Return true if the primary definition of this global value is outside of the current translation unit...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
bool isEHPad() const
Return true if this basic block is an exception handling block.
AnalysisUsage & addUsedIfAvailable()
Add the specified Pass class to the set of analyses used by this pass.
succ_range successors(Instruction *I)
void addFnAttr(Attribute::AttrKind Kind)
Add function attributes to this function.
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
An analysis over an "outer" IR unit that provides access to an analysis manager over an "inner" IR un...