8209171: Simplify Java implementation of Integer/Long.numberOfTrailingZeros()
authorigerasim
Thu, 23 Aug 2018 12:09:46 -0700
changeset 51509 758b3f3f3a8d
parent 51508 f99640a44d75
child 51510 6b0012622443
8209171: Simplify Java implementation of Integer/Long.numberOfTrailingZeros() Reviewed-by: martin Contributed-by: ivan.gerasimov@oracle.com, martinrb@google.com
src/java.base/share/classes/java/lang/Integer.java
src/java.base/share/classes/java/lang/Long.java
--- a/src/java.base/share/classes/java/lang/Integer.java	Thu Aug 23 09:36:13 2018 -0700
+++ b/src/java.base/share/classes/java/lang/Integer.java	Thu Aug 23 12:09:46 2018 -0700
@@ -1654,15 +1654,15 @@
      */
     @HotSpotIntrinsicCandidate
     public static int numberOfTrailingZeros(int i) {
-        // HD, Figure 5-14
-        int y;
-        if (i == 0) return 32;
-        int n = 31;
-        y = i <<16; if (y != 0) { n = n -16; i = y; }
-        y = i << 8; if (y != 0) { n = n - 8; i = y; }
-        y = i << 4; if (y != 0) { n = n - 4; i = y; }
-        y = i << 2; if (y != 0) { n = n - 2; i = y; }
-        return n - ((i << 1) >>> 31);
+        // HD, Count trailing 0's
+        i = ~i & (i - 1);
+        if (i <= 0) return i & 32;
+        int n = 1;
+        if (i > 1 << 16) { n += 16; i >>>= 16; }
+        if (i > 1 <<  8) { n +=  8; i >>>=  8; }
+        if (i > 1 <<  4) { n +=  4; i >>>=  4; }
+        if (i > 1 <<  2) { n +=  2; i >>>=  2; }
+        return n + (i >>> 1);
     }
 
     /**
--- a/src/java.base/share/classes/java/lang/Long.java	Thu Aug 23 09:36:13 2018 -0700
+++ b/src/java.base/share/classes/java/lang/Long.java	Thu Aug 23 12:09:46 2018 -0700
@@ -1782,16 +1782,9 @@
      */
     @HotSpotIntrinsicCandidate
     public static int numberOfTrailingZeros(long i) {
-        // HD, Figure 5-14
-        int x, y;
-        if (i == 0) return 64;
-        int n = 63;
-        y = (int)i; if (y != 0) { n = n -32; x = y; } else x = (int)(i>>>32);
-        y = x <<16; if (y != 0) { n = n -16; x = y; }
-        y = x << 8; if (y != 0) { n = n - 8; x = y; }
-        y = x << 4; if (y != 0) { n = n - 4; x = y; }
-        y = x << 2; if (y != 0) { n = n - 2; x = y; }
-        return n - ((x << 1) >>> 31);
+        int x = (int)i;
+        return x == 0 ? 32 + Integer.numberOfTrailingZeros((int)(i >>> 32))
+                : Integer.numberOfTrailingZeros(x);
     }
 
     /**