1 //===- BranchProbability.h - Branch Probability Wrapper ---------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 // Definition of BranchProbability shared by IR and Machine Instructions.
12 //===----------------------------------------------------------------------===//
14 #ifndef LLVM_SUPPORT_BRANCHPROBABILITY_H
15 #define LLVM_SUPPORT_BRANCHPROBABILITY_H
17 #include "llvm/Support/DataTypes.h"
24 // This class represents Branch Probability as a non-negative fraction.
25 class BranchProbability {
33 BranchProbability(uint32_t n, uint32_t d) : N(n), D(d) {
34 assert(d > 0 && "Denomiator cannot be 0!");
35 assert(n <= d && "Probability cannot be bigger than 1!");
38 static BranchProbability getZero() { return BranchProbability(0, 1); }
39 static BranchProbability getOne() { return BranchProbability(1, 1); }
41 uint32_t getNumerator() const { return N; }
42 uint32_t getDenominator() const { return D; }
44 // Return (1 - Probability).
45 BranchProbability getCompl() const {
46 return BranchProbability(D - N, D);
49 raw_ostream &print(raw_ostream &OS) const;
53 /// \brief Scale a large integer.
55 /// Scales \c Num. Guarantees full precision. Returns the floor of the
58 /// \return \c Num times \c this.
59 uint64_t scale(uint64_t Num) const;
61 /// \brief Scale a large integer by the inverse.
63 /// Scales \c Num by the inverse of \c this. Guarantees full precision.
64 /// Returns the floor of the result.
66 /// \return \c Num divided by \c this.
67 uint64_t scaleByInverse(uint64_t Num) const;
69 bool operator==(BranchProbability RHS) const {
70 return (uint64_t)N * RHS.D == (uint64_t)D * RHS.N;
72 bool operator!=(BranchProbability RHS) const {
73 return !(*this == RHS);
75 bool operator<(BranchProbability RHS) const {
76 return (uint64_t)N * RHS.D < (uint64_t)D * RHS.N;
78 bool operator>(BranchProbability RHS) const { return RHS < *this; }
79 bool operator<=(BranchProbability RHS) const { return !(RHS < *this); }
80 bool operator>=(BranchProbability RHS) const { return !(*this < RHS); }
83 inline raw_ostream &operator<<(raw_ostream &OS, const BranchProbability &Prob) {
84 return Prob.print(OS);