49 #define DEBUG_TYPE "branch-prob" 53 cl::desc(
"Print the branch probability info."));
57 cl::desc(
"The option to specify the name of the function " 58 "whose branch probability info is printed."));
61 "Branch Probability Analysis",
false,
true)
67 BranchProbabilityInfoWrapperPass::BranchProbabilityInfoWrapperPass()
157 for (
auto *BB : Descendants)
158 if (TargetSet.
insert(BB).second)
160 if (!TargetSet.
count(*PI))
166 void BranchProbabilityInfo::computePostDominatedByUnreachable(
172 if (isa<UnreachableInst>(TI) ||
177 BB.getTerminatingDeoptimizeCall())
182 while (!WorkList.
empty()) {
184 if (PostDominatedByUnreachable.count(BB))
189 if (PostDominatedByUnreachable.count(II->getNormalDest()))
195 return PostDominatedByUnreachable.count(Succ);
202 void BranchProbabilityInfo::computePostDominatedByColdCall(
207 if (
const CallInst *CI = dyn_cast<CallInst>(&
I))
211 while (!WorkList.
empty()) {
217 if (PostDominatedByColdCall.count(II->getNormalDest()))
223 return PostDominatedByColdCall.count(Succ);
233 bool BranchProbabilityInfo::calcUnreachableHeuristics(
const BasicBlock *BB) {
237 assert(!isa<InvokeInst>(TI) &&
238 "Invokes should have already been handled by calcInvokeHeuristics");
244 if (PostDominatedByUnreachable.count(*
I))
245 UnreachableEdges.
push_back(
I.getSuccessorIndex());
247 ReachableEdges.
push_back(
I.getSuccessorIndex());
250 if (UnreachableEdges.
empty())
253 if (ReachableEdges.
empty()) {
255 for (
unsigned SuccIdx : UnreachableEdges)
263 ReachableEdges.
size();
265 for (
unsigned SuccIdx : UnreachableEdges)
267 for (
unsigned SuccIdx : ReachableEdges)
277 bool BranchProbabilityInfo::calcMetadataWeights(
const BasicBlock *BB) {
280 if (!(isa<BranchInst>(TI) || isa<SwitchInst>(TI) || isa<IndirectBrInst>(TI)))
298 uint64_t WeightSum = 0;
305 mdconst::dyn_extract<ConstantInt>(WeightsNode->
getOperand(i));
309 "Too many bits for uint32_t");
311 WeightSum += Weights.
back();
312 if (PostDominatedByUnreachable.count(TI->
getSuccessor(i - 1)))
321 uint64_t ScalingFactor =
322 (WeightSum > UINT32_MAX) ? WeightSum / UINT32_MAX + 1 : 1;
324 if (ScalingFactor > 1) {
327 Weights[i] /= ScalingFactor;
328 WeightSum += Weights[i];
331 assert(WeightSum <= UINT32_MAX &&
332 "Expected weights to scale down to 32 bits");
334 if (WeightSum == 0 || ReachableIdxs.
size() == 0) {
343 BP.
push_back({ Weights[i], static_cast<uint32_t>(WeightSum) });
347 if (UnreachableIdxs.
size() > 0 && ReachableIdxs.
size() > 0) {
350 for (
auto i : UnreachableIdxs)
351 if (UnreachableProb < BP[i]) {
352 ToDistribute += BP[i] - UnreachableProb;
353 BP[i] = UnreachableProb;
360 for (
auto i : ReachableIdxs)
379 bool BranchProbabilityInfo::calcColdCallHeuristics(
const BasicBlock *BB) {
383 assert(!isa<InvokeInst>(TI) &&
384 "Invokes should have already been handled by calcInvokeHeuristics");
390 if (PostDominatedByColdCall.count(*
I))
396 if (ColdEdges.
empty())
399 if (NormalEdges.
empty()) {
401 for (
unsigned SuccIdx : ColdEdges)
408 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(ColdEdges.
size()));
411 (CC_TAKEN_WEIGHT + CC_NONTAKEN_WEIGHT) * uint64_t(NormalEdges.
size()));
413 for (
unsigned SuccIdx : ColdEdges)
415 for (
unsigned SuccIdx : NormalEdges)
423 bool BranchProbabilityInfo::calcPointerHeuristics(
const BasicBlock *BB) {
444 unsigned TakenIdx = 0, NonTakenIdx = 1;
450 PH_TAKEN_WEIGHT + PH_NONTAKEN_WEIGHT);
461 return SccIt->second;
471 if (SccI.
SccHeaders.size() <=
static_cast<unsigned>(SccNum))
476 std::tie(HeaderMapIt, Inserted) = HeaderMap.insert(std::make_pair(BB,
false));
482 HeaderMapIt->second = IsHeader;
485 return HeaderMapIt->second;
521 if (!CI || !isa<Instruction>(CI->
getOperand(0)) ||
533 while (!CmpPHI && CmpLHS && isa<BinaryOperator>(CmpLHS) &&
538 InstChain.
push_back(cast<BinaryOperator>(CmpLHS));
543 if (!CmpPHI || !L->
contains(CmpPHI))
550 VisitedInsts.
insert(CmpPHI);
551 while (!WorkList.
empty()) {
561 if (
PHINode *PN = dyn_cast<PHINode>(V)) {
562 if (VisitedInsts.
insert(PN).second)
576 cast<Constant>(
I->getOperand(1)),
true);
584 CmpLHSConst, CmpConst,
true);
597 bool BranchProbabilityInfo::calcLoopBranchHeuristics(
const BasicBlock *BB,
621 if (UnlikelyBlocks.
count(*
I) != 0)
622 UnlikelyEdges.
push_back(
I.getSuccessorIndex());
624 ExitingEdges.
push_back(
I.getSuccessorIndex());
631 ExitingEdges.
push_back(
I.getSuccessorIndex());
639 if (BackEdges.
empty() && ExitingEdges.
empty() && UnlikelyEdges.
empty())
651 auto Prob = TakenProb / numBackEdges;
652 for (
unsigned SuccIdx : BackEdges)
658 auto Prob = TakenProb / numInEdges;
659 for (
unsigned SuccIdx : InEdges)
666 auto Prob = NotTakenProb / numExitingEdges;
667 for (
unsigned SuccIdx : ExitingEdges)
674 auto Prob = UnlikelyProb / numUnlikelyEdges;
675 for (
unsigned SuccIdx : UnlikelyEdges)
682 bool BranchProbabilityInfo::calcZeroHeuristics(
const BasicBlock *BB,
694 if (
auto *
I = dyn_cast<BitCastInst>(V))
695 return dyn_cast<ConstantInt>(
I->getOperand(0));
707 if (LHS->getOpcode() == Instruction::And)
708 if (ConstantInt *AndRHS = dyn_cast<ConstantInt>(LHS->getOperand(1)))
709 if (AndRHS->getValue().isPowerOf2())
716 if (
Function *CalledFn = Call->getCalledFunction())
720 if (Func == LibFunc_strcasecmp ||
721 Func == LibFunc_strcmp ||
722 Func == LibFunc_strncasecmp ||
723 Func == LibFunc_strncmp ||
724 Func == LibFunc_memcmp) {
742 }
else if (CV->
isZero()) {
789 unsigned TakenIdx = 0, NonTakenIdx = 1;
795 ZH_TAKEN_WEIGHT + ZH_NONTAKEN_WEIGHT);
801 bool BranchProbabilityInfo::calcFloatingPointHeuristics(
const BasicBlock *BB) {
832 unsigned TakenIdx = 0, NonTakenIdx = 1;
843 bool BranchProbabilityInfo::calcInvokeHeuristics(
const BasicBlock *BB) {
849 IH_TAKEN_WEIGHT + IH_NONTAKEN_WEIGHT);
860 OS <<
"---- Branch Probabilities ----\n";
863 assert(LastF &&
"Cannot print prior to running over a function");
864 for (
const auto &BI : *LastF) {
887 if (Prob > MaxProb) {
906 unsigned IndexInSuccessors)
const {
907 auto I = Probs.find(std::make_pair(Src, IndexInSuccessors));
909 if (
I != Probs.end())
912 return {1, static_cast<uint32_t>(
succ_size(Src))};
927 bool FoundProb =
false;
930 auto MapI = Probs.find(std::make_pair(Src,
I.getSuccessorIndex()));
931 if (MapI != Probs.end()) {
933 Prob += MapI->second;
943 unsigned IndexInSuccessors,
945 Probs[std::make_pair(Src, IndexInSuccessors)] = Prob;
946 Handles.insert(BasicBlockCallbackVH(Src,
this));
948 << IndexInSuccessors <<
" successor probability to " << Prob
958 <<
" probability is " << Prob
959 << (
isEdgeHot(Src, Dst) ?
" [HOT edge]\n" :
"\n");
965 for (
auto I = Probs.begin(),
E = Probs.end();
I !=
E; ++
I) {
977 assert(PostDominatedByUnreachable.empty());
978 assert(PostDominatedByColdCall.empty());
989 const std::vector<const BasicBlock *> &Scc = *It;
994 for (
auto *BB : Scc) {
1001 std::unique_ptr<PostDominatorTree> PDT =
1002 std::make_unique<PostDominatorTree>(
const_cast<Function &
>(
F));
1003 computePostDominatedByUnreachable(F, PDT.get());
1004 computePostDominatedByColdCall(F, PDT.get());
1009 LLVM_DEBUG(
dbgs() <<
"Computing probabilities for " << BB->getName()
1012 if (BB->getTerminator()->getNumSuccessors() < 2)
1014 if (calcMetadataWeights(BB))
1016 if (calcInvokeHeuristics(BB))
1018 if (calcUnreachableHeuristics(BB))
1020 if (calcColdCallHeuristics(BB))
1022 if (calcLoopBranchHeuristics(BB, LI, SccI))
1024 if (calcPointerHeuristics(BB))
1026 if (calcZeroHeuristics(BB, TLI))
1028 if (calcFloatingPointHeuristics(BB))
1032 PostDominatedByUnreachable.clear();
1033 PostDominatedByColdCall.clear();
1054 const LoopInfo &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
1056 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
1057 BPI.calculate(F, LI, &TLI);
1078 OS <<
"Printing analysis results of BPI for function "
static bool isEquality(Predicate Pred)
This builds on the llvm/ADT/GraphTraits.h file to find the strongly connected components (SCCs) of a ...
This class is the base class for the comparison instructions.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
BranchProbability getCompl() const
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.
A Module instance is used to store all the information related to an LLVM module. ...
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
void calculate(const Function &F, const LoopInfo &LI, const TargetLibraryInfo *TLI=nullptr)
static BranchProbability getRaw(uint32_t N)
void push_back(const T &Elt)
int getSuccessorIndex() const
This is used to interface between code that wants to operate on terminator instructions directly...
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...
BasicBlock * getSuccessor(unsigned i) const
static bool isEquality(Predicate P)
Return true if this predicate is either EQ or NE.
const MDOperand & getOperand(unsigned I) const
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
block Block Frequency true
static Constant * getCompare(unsigned short pred, Constant *C1, Constant *C2, bool OnlyIfReduced=false)
Return an ICmp or FCmp comparison operator constant expression.
Value * getCondition() const
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...
static BranchProbability getOne()
void reserve(size_type N)
static ConstantInt * GetConstantInt(Value *V, const DataLayout &DL)
Extract ConstantInt from value, looking through IntToPtr and PointerNullValue.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
1 0 0 0 True if unordered: isnan(X) | isnan(Y)
const BasicBlock * getHotSucc(const BasicBlock *BB) const
Retrieve the hot successor of a block if one exists.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
INITIALIZE_PASS_BEGIN(BranchProbabilityInfoWrapperPass, "branch-prob", "Branch Probability Analysis", false, true) INITIALIZE_PASS_END(BranchProbabilityInfoWrapperPass
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
static int getSCCNum(const BasicBlock *BB, const BranchProbabilityInfo::SccInfo &SccI)
This file contains the simple types necessary to represent the attributes associated with functions a...
Analysis pass that exposes the LoopInfo for a function.
BlockT * getHeader() 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...
scc_iterator< T > scc_begin(const T &G)
Construct the begin iterator for a deduced graph type T.
Analysis pass which computes BranchProbabilityInfo.
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
unsigned getActiveBits() const
Compute the number of active bits in the value.
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Type * getType() const
All values are typed, get the type of this value.
This instruction compares its operands according to the predicate given to the constructor.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
const APInt & getValue() const
Return the constant as an APInt value reference.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
Legacy analysis pass which computes BranchProbabilityInfo.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Interval::succ_iterator succ_end(Interval *I)
iterator find(const_arg_type_t< KeyT > Val)
bool isZeroValue() const
Return true if the value is negative zero or null value.
const BasicBlock & getEntryBlock() const
initializer< Ty > init(const Ty &Val)
void initializeBranchProbabilityInfoWrapperPassPass(PassRegistry &)
static void UpdatePDTWorklist(const BasicBlock *BB, PostDominatorTree *PDT, SmallVectorImpl< const BasicBlock *> &WorkList, SmallPtrSetImpl< const BasicBlock *> &TargetSet)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
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.
void getDescendants(NodeT *R, SmallVectorImpl< NodeT *> &Result) const
Get all nodes dominated by R, including R itself.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
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 any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
static void computeUnlikelySuccessors(const BasicBlock *BB, Loop *L, SmallPtrSetImpl< const BasicBlock *> &UnlikelyBlocks)
This instruction compares its operands according to the predicate given to the constructor.
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
0 1 1 1 True if ordered (no nans)
iterator_range< po_iterator< T > > post_order(const T &G)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
iterator_range< block_iterator > blocks()
static const uint32_t ZH_NONTAKEN_WEIGHT
BranchProbabilityInfo run(Function &F, FunctionAnalysisManager &AM)
Run the analysis pass over a function and produce BPI.
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
BranchProbability getEdgeProbability(const BasicBlock *Src, unsigned IndexInSuccessors) const
Get an edge's probability, relative to other out-edges of the Src.
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
static bool isSCCHeader(const BasicBlock *BB, int SccNum, BranchProbabilityInfo::SccInfo &SccI)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
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.
LLVM_NODISCARD T pop_back_val()
bool isConditional() const
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.
bool isTrueWhenEqual() const
This is just a convenience.
void print(raw_ostream &OS) const
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.
bool getLibFunc(StringRef funcName, LibFunc &F) const
Searches for a particular function name.
PostDominatorTree Class - Concrete subclass of DominatorTree that is used to compute the post-dominat...
iterator insert(iterator I, T &&Elt)
static const uint32_t FPH_UNO_WEIGHT
This is the probability for an unordered floating point comparison, it means one or two of the operan...
LLVM_NODISCARD bool equals(StringRef RHS) const
equals - Check for string equality, this is more efficient than compare() when the relative ordering ...
static const uint32_t IH_TAKEN_WEIGHT
Invoke-terminating normal branch taken weight.
unsigned succ_size(const Instruction *I)
Predicate getPredicate() const
Return the predicate for this instruction.
This file provides various utilities for inspecting and working with the control flow graph in LLVM I...
Analysis providing branch probability information.
static const uint32_t LBH_UNLIKELY_WEIGHT
static const uint32_t PH_NONTAKEN_WEIGHT
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
static const uint32_t LBH_NONTAKEN_WEIGHT
DenseMapIterator< const BasicBlock *, bool, DenseMapInfo< const BasicBlock * >, llvm::detail::DenseMapPair< const BasicBlock *, bool > > iterator
StringRef getName() const
Return a constant reference to the value's name.
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...
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Analysis pass providing the TargetLibraryInfo.
bool isOneValue() const
Returns true if the value is one.
static const uint32_t CC_NONTAKEN_WEIGHT
Weight for a branch not-taken into a cold block.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static const uint32_t FPH_ORD_WEIGHT
This is the probability for an ordered floating point comparison.
LLVM Value Representation.
bool isEdgeHot(const BasicBlock *Src, const BasicBlock *Dst) const
Test if an edge is hot relative to other out-edges of the Src.
static const uint32_t ZH_TAKEN_WEIGHT
succ_range successors(Instruction *I)
static const uint32_t PH_TAKEN_WEIGHT
raw_ostream & printEdgeProbability(raw_ostream &OS, const BasicBlock *Src, const BasicBlock *Dst) const
Print an edge's probability.
This class implements an extremely fast bulk output stream that can only output to a stream...
The legacy pass manager's analysis pass to compute loop information.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
static BranchProbability getZero()
cl::opt< std::string > PrintBranchProbFuncName("print-bpi-func-name", cl::Hidden, cl::desc("The option to specify the name of the function " "whose branch probability info is printed."))
This header defines various interfaces for pass management in LLVM.
unsigned getNumOperands() const
Return number of MDNode operands.
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...
static cl::opt< bool > PrintBranchProb("print-bpi", cl::init(false), cl::Hidden, cl::desc("Print the branch probability info."))
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Enumerate the SCCs of a directed graph in reverse topological order of the SCC DAG.
static Constant * get(unsigned Opcode, Constant *C1, unsigned Flags=0, Type *OnlyIfReducedTy=nullptr)
get - Return a unary operator constant expression, folding if possible.