29 #define DEBUG_TYPE "branch-prob"
32 "Branch Probability Analysis",
false,
true)
38 char BranchProbabilityInfoWrapperPass::
ID = 0;
111 if (isa<UnreachableInst>(TI) ||
116 BB->getTerminatingDeoptimizeCall())
117 PostDominatedByUnreachable.insert(BB);
123 if (
auto *II = dyn_cast<InvokeInst>(TI)) {
124 if (PostDominatedByUnreachable.count(II->getNormalDest()))
125 PostDominatedByUnreachable.insert(BB);
131 if (!PostDominatedByUnreachable.count(
I))
134 PostDominatedByUnreachable.insert(BB);
139 BranchProbabilityInfo::updatePostDominatedByColdCall(
const BasicBlock *BB) {
140 assert(!PostDominatedByColdCall.count(BB));
142 if (TI->getNumSuccessors() == 0)
147 return PostDominatedByColdCall.count(SuccBB);
149 PostDominatedByColdCall.insert(BB);
155 if (
auto *II = dyn_cast<InvokeInst>(TI))
156 if (PostDominatedByColdCall.count(II->getNormalDest())) {
157 PostDominatedByColdCall.insert(BB);
164 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
166 PostDominatedByColdCall.insert(BB);
175 bool BranchProbabilityInfo::calcUnreachableHeuristics(
const BasicBlock *BB) {
181 if (isa<InvokeInst>(TI))
188 if (PostDominatedByUnreachable.count(*
I))
189 UnreachableEdges.
push_back(
I.getSuccessorIndex());
191 ReachableEdges.
push_back(
I.getSuccessorIndex());
194 if (UnreachableEdges.
empty())
197 if (ReachableEdges.
empty()) {
199 for (
unsigned SuccIdx : UnreachableEdges)
207 ReachableEdges.
size();
209 for (
unsigned SuccIdx : UnreachableEdges)
211 for (
unsigned SuccIdx : ReachableEdges)
221 bool BranchProbabilityInfo::calcMetadataWeights(
const BasicBlock *BB) {
224 if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))
242 uint64_t WeightSum = 0;
247 for (
unsigned i = 1, e = WeightsNode->
getNumOperands(); i != e; ++i) {
249 mdconst::dyn_extract<ConstantInt>(WeightsNode->
getOperand(i));
253 "Too many bits for uint32_t");
255 WeightSum += Weights.
back();
256 if (PostDominatedByUnreachable.count(TI->
getSuccessor(i - 1)))
265 uint64_t ScalingFactor =
266 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
268 if (ScalingFactor > 1) {
271 Weights[i] /= ScalingFactor;
272 WeightSum += Weights[i];
275 assert(WeightSum <= UINT32_MAX &&
276 "Expected weights to scale down to 32 bits");
278 if (WeightSum == 0 || ReachableIdxs.
size() == 0) {
287 BP.
push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
291 if (UnreachableIdxs.
size() > 0 && ReachableIdxs.
size() > 0) {
294 for (
auto i : UnreachableIdxs)
295 if (UnreachableProb < BP[i]) {
296 ToDistribute += BP[i] - UnreachableProb;
297 BP[i] = UnreachableProb;
304 for (
auto i : ReachableIdxs)
310 setEdgeProbability(BB, i, BP[i]);
323 bool BranchProbabilityInfo::calcColdCallHeuristics(
const BasicBlock *BB) {
329 if (isa<InvokeInst>(TI))
336 if (PostDominatedByColdCall.count(*
I))
342 if (ColdEdges.
empty())
345 if (NormalEdges.
empty()) {
347 for (
unsigned SuccIdx : ColdEdges)
359 for (
unsigned SuccIdx : ColdEdges)
361 for (
unsigned SuccIdx : NormalEdges)
369 bool BranchProbabilityInfo::calcPointerHeuristics(
const BasicBlock *BB) {
390 unsigned TakenIdx = 0, NonTakenIdx = 1;
404 bool BranchProbabilityInfo::calcLoopBranchHeuristics(
const BasicBlock *BB,
416 ExitingEdges.
push_back(
I.getSuccessorIndex());
423 if (BackEdges.
empty() && ExitingEdges.
empty())
434 if (!BackEdges.
empty())
436 if (!InEdges.
empty())
438 if (!ExitingEdges.
empty())
442 auto Prob = Probs[0] / numBackEdges;
443 for (
unsigned SuccIdx : BackEdges)
448 auto Prob = Probs[1] / numInEdges;
449 for (
unsigned SuccIdx : InEdges)
454 auto Prob = Probs[2] / numExitingEdges;
455 for (
unsigned SuccIdx : ExitingEdges)
462 bool BranchProbabilityInfo::calcZeroHeuristics(
const BasicBlock *BB,
481 if (LHS->getOpcode() == Instruction::And)
482 if (
ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
483 if (AndRHS->getUniqueInteger().isPowerOf2())
494 if (Func == LibFunc_strcasecmp ||
495 Func == LibFunc_strcmp ||
496 Func == LibFunc_strncasecmp ||
497 Func == LibFunc_strncmp ||
498 Func == LibFunc_memcmp) {
516 }
else if (CV->
isZero()) {
563 unsigned TakenIdx = 0, NonTakenIdx = 1;
575 bool BranchProbabilityInfo::calcFloatingPointHeuristics(
const BasicBlock *BB) {
600 unsigned TakenIdx = 0, NonTakenIdx = 1;
612 bool BranchProbabilityInfo::calcInvokeHeuristics(
const BasicBlock *BB) {
629 OS <<
"---- Branch Probabilities ----\n";
632 assert(LastF &&
"Cannot print prior to running over a function");
633 for (
const auto &BI : *LastF) {
656 if (Prob > MaxProb) {
675 unsigned IndexInSuccessors)
const {
676 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
678 if (
I != Probs.end())
697 bool FoundProb =
false;
700 auto MapI = Probs.find(std::make_pair(Src,
I.getSuccessorIndex()));
701 if (MapI != Probs.end()) {
703 Prob += MapI->second;
713 unsigned IndexInSuccessors,
715 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
716 Handles.insert(BasicBlockCallbackVH(Src,
this));
717 DEBUG(
dbgs() <<
"set edge " << Src->
getName() <<
" -> " << IndexInSuccessors
718 <<
" successor probability to " << Prob <<
"\n");
728 <<
" probability is " << Prob
729 << (
isEdgeHot(Src, Dst) ?
" [HOT edge]\n" :
"\n");
735 for (
auto I = Probs.begin(),
E = Probs.end();
I !=
E; ++
I) {
747 assert(PostDominatedByUnreachable.empty());
748 assert(PostDominatedByColdCall.empty());
754 updatePostDominatedByUnreachable(BB);
755 updatePostDominatedByColdCall(BB);
759 if (calcMetadataWeights(BB))
761 if (calcUnreachableHeuristics(BB))
763 if (calcColdCallHeuristics(BB))
765 if (calcLoopBranchHeuristics(BB, LI))
767 if (calcPointerHeuristics(BB))
769 if (calcZeroHeuristics(BB, TLI))
771 if (calcFloatingPointHeuristics(BB))
773 calcInvokeHeuristics(BB);
776 PostDominatedByUnreachable.clear();
777 PostDominatedByColdCall.clear();
788 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
789 const TargetLibraryInfo &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
811 OS <<
"Printing analysis results of BPI for function "
void push_back(const T &Elt)
static bool isEquality(Predicate Pred)
raw_ostream & printEdgeProbability(raw_ostream &OS, const BasicBlock *Src, const BasicBlock *Dst) const
Print an edge's probability.
const BasicBlock * getHotSucc(const BasicBlock *BB) const
Retrieve the hot successor of a block if one exists.
A Module instance is used to store all the information related to an LLVM module. ...
void calculate(const Function &F, const LoopInfo &LI, const TargetLibraryInfo *TLI=nullptr)
unsigned getNumOperands() const
Return number of MDNode operands.
This class represents a function call, abstracting a target machine's calling convention.
static const uint32_t FPH_TAKEN_WEIGHT
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
static BranchProbability getOne()
void reserve(size_type N)
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
BlockT * getHeader() const
StringRef getName() const
Return a constant reference to the value's name.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
branch Branch Probability false
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
const APInt & getValue() const
Return the constant as an APInt value reference.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
Analysis pass that exposes the LoopInfo for a function.
LLVM_NODISCARD bool empty() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
Analysis pass which computes BranchProbabilityInfo.
This instruction compares its operands according to the predicate given to the constructor.
unsigned getActiveBits() const
Compute the number of active bits in the value.
Legacy analysis pass which computes BranchProbabilityInfo.
Interval::succ_iterator succ_end(Interval *I)
Subclasses of this class are all able to terminate a basic block.
A set of analyses that are preserved following a run of a transformation pass.
static const uint32_t IH_NONTAKEN_WEIGHT
Invoke-terminating normal branch not-taken weight.
LLVM Basic Block Representation.
Conditional or Unconditional Branch instruction.
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static const uint32_t CC_TAKEN_WEIGHT
Weight for a branch taken going into a cold block.
void eraseBlock(const BasicBlock *BB)
Forget analysis results for the given basic block.
Represent the analysis usage information of a pass.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
This instruction compares its operands according to the predicate given to the constructor.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * getOperand(unsigned i) const
0 1 1 1 True if ordered (no nans)
iterator_range< po_iterator< T > > post_order(const T &G)
Predicate getPredicate() const
Return the predicate for this instruction.
static const uint32_t ZH_NONTAKEN_WEIGHT
BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BPI.
bool isPointerTy() const
True if this is an instance of PointerType.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
bool isConditional() const
const MDOperand & getOperand(unsigned I) const
This is the shared class of boolean and integer constants.
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
static BranchProbability getBranchProbability(uint64_t Numerator, uint64_t Denominator)
void setEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors, BranchProbability Prob)
Set the raw edge probability for the given edge.
bool isTrueWhenEqual() const
This is just a convenience.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
const BasicBlock & getEntryBlock() const
bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
branch Branch Probability Analysis
void print(raw_ostream &OS) const
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static const uint32_t FPH_NONTAKEN_WEIGHT
void setPreservesAll()
Set by analyses that do not transform their input at all.
static const BranchProbability UR_TAKEN_PROB
Unreachable-terminating branch taken probability.
static const uint32_t IH_TAKEN_WEIGHT
Invoke-terminating normal branch taken weight.
Value * getCondition() const
Analysis providing branch probability information.
static const uint32_t PH_NONTAKEN_WEIGHT
Represents a single loop in the control flow graph.
static const uint32_t LBH_NONTAKEN_WEIGHT
static const uint32_t LBH_TAKEN_WEIGHT
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass,"branch-prob","Branch Probability Analysis", false, true) INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass
Analysis pass providing the TargetLibraryInfo.
static const uint32_t CC_NONTAKEN_WEIGHT
Weight for a branch not-taken into a cold block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
LLVM Value Representation.
succ_range successors(BasicBlock *BB)
static const uint32_t ZH_TAKEN_WEIGHT
unsigned getSuccessorIndex() const
This is used to interface between code that wants to operate on terminator instructions directly...
static const uint32_t PH_TAKEN_WEIGHT
This class implements an extremely fast bulk output stream that can only output to a stream...
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
The legacy pass manager's analysis pass to compute loop information.
A container for analyses that lazily runs them and caches their results.
static BranchProbability getZero()
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
A special type used by analysis passes to provide an address that identifies that particular analysis...
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)