Merge ktlim@zizzer.eecs.umich.edu:/bk/m5
[gem5.git] / base / intmath.hh
index 16467426d6515f994052b83ce68ef67cbbd9e236..5ffe2710393c78cd5d746f4e3a60f42f6d19caf0 100644 (file)
@@ -1,5 +1,5 @@
 /*
- * Copyright (c) 2003 The Regents of The University of Michigan
+ * Copyright (c) 2001, 2003 The Regents of The University of Michigan
  * All rights reserved.
  *
  * Redistribution and use in source and binary forms, with or without
 #ifndef __INTMATH_HH__
 #define __INTMATH_HH__
 
+#include <assert.h>
+
+#include "sim/host.hh"
+
 // Returns the prime number one less than n.
 int PrevPrime(int n);
 
@@ -68,12 +72,10 @@ IsPowerOf2(T n)
     return n != 0 && LeastSigBit(n) == n;
 }
 
-template <class T>
 inline int
-FloorLog2(T x)
+FloorLog2(uint32_t x)
 {
-    if (x == 0)
-        return -1;
+    assert(x > 0);
 
     int y = 0;
 
@@ -86,11 +88,61 @@ FloorLog2(T x)
     return y;
 }
 
+inline int
+FloorLog2(uint64_t x)
+{
+    assert(x > 0);
+
+    int y = 0;
+
+    if (x & ULL(0xffffffff00000000)) { y += 32; x >>= 32; }
+    if (x & ULL(0x00000000ffff0000)) { y += 16; x >>= 16; }
+    if (x & ULL(0x000000000000ff00)) { y +=  8; x >>=  8; }
+    if (x & ULL(0x00000000000000f0)) { y +=  4; x >>=  4; }
+    if (x & ULL(0x000000000000000c)) { y +=  2; x >>=  2; }
+    if (x & ULL(0x0000000000000002)) { y +=  1; }
+
+    return y;
+}
+
+inline int
+FloorLog2(int32_t x)
+{
+    assert(x > 0);
+    return FloorLog2((uint32_t)x);
+}
+
+inline int
+FloorLog2(int64_t x)
+{
+    assert(x > 0);
+    return FloorLog2((uint64_t)x);
+}
+
+#if defined(__APPLE__)
+inline int
+FloorLog2(size_t x)
+{
+    assert(x > 0);
+    assert(sizeof(size_t) == 4 || sizeof(size_t) == 8);
+
+    // It's my hope that this is optimized away?
+    if (sizeof(size_t) == 4)
+        return FloorLog2((uint32_t)x);
+     else if (sizeof(size_t) == 8)
+        return FloorLog2((uint64_t)x);
+
+}
+#endif
+
 template <class T>
 inline int
 CeilLog2(T n)
 {
-    return FloorLog2(n - 1) + 1;
+    if (n == 1)
+        return 0;
+
+    return FloorLog2(n - (T)1) + 1;
 }
 
 template <class T>
@@ -107,6 +159,29 @@ CeilPow2(T n)
     return (T)1 << CeilLog2(n);
 }
 
+template <class T>
+inline T
+DivCeil(T a, T b)
+{
+    return (a + b - 1) / b;
+}
+
+template <class T>
+inline T
+RoundUp(T val, T align)
+{
+    T mask = align - 1;
+    return (val + mask) & ~mask;
+}
+
+template <class T>
+inline T
+RoundDown(T val, T align)
+{
+    T mask = align - 1;
+    return val & ~mask;
+}
+
 inline bool
 IsHex(char c)
 {
@@ -133,7 +208,7 @@ Hex2Int(char c)
   if (c >= '0' && c <= '9')
     return (c - '0');
 
-  if(c >= 'A' && c <= 'F')
+  if (c >= 'A' && c <= 'F')
     return (c - 'A') + 10;
 
   if (c >= 'a' && c <= 'f')