Let += and -= operators in BranchProbability have saturation behaviors.
authorCong Hou <congh@google.com>
Wed, 18 Nov 2015 01:20:37 +0000 (01:20 +0000)
committerCong Hou <congh@google.com>
Wed, 18 Nov 2015 01:20:37 +0000 (01:20 +0000)
This commit is for a later patch that is depend on it. The sum of two
branch probabilities can be greater than 1 due to rounding. It is safer
to saturate the results of sum and subtraction.

git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@253421 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Support/BranchProbability.h

index 71c0cf9afea82442e729b3da4d160d08d6e7eb0f..1ca94ca3196fc50b372e10712a6404eac853cdf1 100644 (file)
@@ -92,16 +92,14 @@ public:
   uint64_t scaleByInverse(uint64_t Num) const;
 
   BranchProbability &operator+=(BranchProbability RHS) {
-    assert(N <= D - RHS.N &&
-           "The sum of branch probabilities should not exceed one!");
-    N += RHS.N;
+    // Saturate the result in case of overflow.
+    N = (uint64_t(N) + RHS.N > D) ? D : N + RHS.N;
     return *this;
   }
 
   BranchProbability &operator-=(BranchProbability RHS) {
-    assert(N >= RHS.N &&
-           "Can only subtract a smaller probability from a larger one!");
-    N -= RHS.N;
+    // Saturate the result in case of underflow.
+    N = N < RHS.N ? 0 : N - RHS.N;
     return *this;
   }