Don't wipe out global variables that are probably storing pointers to heap
[oota-llvm.git] / lib / Support / BlockFrequency.cpp
index 87e1b2dba0624b8e41c1fe7d8fa512d0be1709b0..84a993e3e5b6fd6a54dad76dc982b2c7ced36cf1 100644 (file)
 
 using namespace llvm;
 
+namespace {
+
 /// mult96bit - Multiply FREQ by N and store result in W array.
-void BlockFrequency::mult96bit(uint64_t freq, uint32_t N, uint64_t W[2]) {
+void mult96bit(uint64_t freq, uint32_t N, uint64_t W[2]) {
   uint64_t u0 = freq & UINT32_MAX;
   uint64_t u1 = freq >> 32;
 
@@ -41,11 +43,12 @@ void BlockFrequency::mult96bit(uint64_t freq, uint32_t N, uint64_t W[2]) {
 
 
 /// div96bit - Divide 96-bit value stored in W array by D. Return 64-bit frequency.
-uint64_t BlockFrequency::div96bit(uint64_t W[2], uint32_t D) {
+uint64_t div96bit(uint64_t W[2], uint32_t D) {
   uint64_t y = W[0];
   uint64_t x = W[1];
+  int i;
 
-  for (int i = 1; i <= 64; ++i) {
+  for (i = 1; i <= 64 && x; ++i) {
     uint32_t t = (int)x >> 31;
     x = (x << 1) | (y >> 63);
     y = y << 1;
@@ -55,17 +58,25 @@ uint64_t BlockFrequency::div96bit(uint64_t W[2], uint32_t D) {
     }
   }
 
-  return y;
+  return y << (64 - i + 1);
+}
+
 }
 
+
 BlockFrequency &BlockFrequency::operator*=(const BranchProbability &Prob) {
   uint32_t n = Prob.getNumerator();
   uint32_t d = Prob.getDenominator();
 
   assert(n <= d && "Probability must be less or equal to 1.");
 
-  // If we can overflow use 96-bit operations.
-  if (n > 0 && Frequency > UINT64_MAX / n) {
+  // Calculate Frequency * n.
+  uint64_t mulLo = (Frequency & UINT32_MAX) * n;
+  uint64_t mulHi = (Frequency >> 32) * n;
+  uint64_t mulRes = (mulHi << 32) + mulLo;
+
+  // If there was overflow use 96-bit operations.
+  if (mulHi > UINT32_MAX || mulRes < mulLo) {
     // 96-bit value represented as W[1]:W[0].
     uint64_t W[2];
 
@@ -76,8 +87,7 @@ BlockFrequency &BlockFrequency::operator*=(const BranchProbability &Prob) {
     return *this;
   }
 
-  Frequency *= n;
-  Frequency /= d;
+  Frequency = mulRes / d;
   return *this;
 }