Add - and -= operators to BlockFrequency using saturating arithmetic.
authorCong Hou <congh@google.com>
Mon, 12 Oct 2015 18:34:00 +0000 (18:34 +0000)
committerCong Hou <congh@google.com>
Mon, 12 Oct 2015 18:34:00 +0000 (18:34 +0000)
git-svn-id: https://llvm.org/svn/llvm-project/llvm/trunk@250077 91177308-0d34-0410-b5e6-96231b3b80d8

include/llvm/Support/BlockFrequency.h
lib/Support/BlockFrequency.cpp
unittests/Support/BlockFrequencyTest.cpp

index 2dccfa2..1b45cc5 100644 (file)
@@ -49,6 +49,10 @@ public:
   BlockFrequency &operator+=(BlockFrequency Freq);
   BlockFrequency operator+(BlockFrequency Freq) const;
 
+  /// \brief Subtracts another block frequency using saturating arithmetic.
+  BlockFrequency &operator-=(BlockFrequency Freq);
+  BlockFrequency operator-(BlockFrequency Freq) const;
+
   /// \brief Shift block frequency to the right by count digits saturating to 1.
   BlockFrequency &operator>>=(const unsigned count);
 
index e0430c1..e7f3e17 100644 (file)
@@ -56,6 +56,21 @@ BlockFrequency BlockFrequency::operator+(BlockFrequency Freq) const {
   return NewFreq;
 }
 
+BlockFrequency &BlockFrequency::operator-=(BlockFrequency Freq) {
+  // If underflow, set frequency to 0.
+  if (Frequency <= Freq.Frequency)
+    Frequency = 0;
+  else
+    Frequency -= Freq.Frequency;
+  return *this;
+}
+
+BlockFrequency BlockFrequency::operator-(BlockFrequency Freq) const {
+  BlockFrequency NewFreq(Frequency);
+  NewFreq -= Freq;
+  return NewFreq;
+}
+
 BlockFrequency &BlockFrequency::operator>>=(const unsigned count) {
   // Frequency can never be 0 by design.
   assert(Frequency != 0);
index c3273bf..c1f5671 100644 (file)
@@ -88,6 +88,12 @@ TEST(BlockFrequencyTest, MaxToMax) {
   EXPECT_EQ(Freq.getFrequency(), UINT64_MAX);
 }
 
+TEST(BlockFrequencyTest, Subtract) {
+  BlockFrequency Freq1(0), Freq2(1);
+  EXPECT_EQ((Freq1 - Freq2).getFrequency(), 0u);
+  EXPECT_EQ((Freq2 - Freq1).getFrequency(), 1u);
+}
+
 TEST(BlockFrequency, Divide) {
   BlockFrequency Freq(0x3333333333333333ULL);
   Freq /= BranchProbability(1, 2);