Skip to content
Permalink
Browse files
8241018: 32-bit integer log2 functions return the wrong value for neg…
…ative arguments on 64-bit machines

Reviewed-by: kvn
  • Loading branch information
Andrew Haley committed Mar 16, 2020
1 parent 2b4b3d9 commit 195361216c5c334034b6640dd6213ba47584cd20
Showing with 37 additions and 2 deletions.
  1. +2 −2 src/hotspot/share/utilities/globalDefinitions.hpp
  2. +35 −0 test/hotspot/gtest/utilities/test_globalDefinitions.cpp
@@ -1022,12 +1022,12 @@ inline int log2_intptr(intptr_t x) {

inline int log2_int(int x) {
STATIC_ASSERT(sizeof(int) <= sizeof(uintptr_t));
return log2_intptr((uintptr_t)x);
return log2_intptr((uintptr_t)(unsigned int)x);
}

inline int log2_jint(jint x) {
STATIC_ASSERT(sizeof(jint) <= sizeof(uintptr_t));
return log2_intptr((uintptr_t)x);
return log2_intptr((uintptr_t)(juint)x);
}

inline int log2_uint(uint x) {
@@ -188,3 +188,38 @@ TEST(globalDefinitions, byte_size_in_exact_unit) {
EXPECT_EQ(M + K + 1, byte_size_in_exact_unit(G + M + K));
#endif
}

#define EXPECT_EQ_LOG2(fn, type) \
{ \
int limit = sizeof (type) * BitsPerByte; \
if (IsSigned<type>::value) { \
EXPECT_EQ(limit - 1, fn(std::numeric_limits<type>::min())); \
EXPECT_EQ(limit - 1, fn((type)-1)); \
limit--; \
} \
{ \
/* Test the all-1s bit patterns */ \
type var = 1; \
for (int i = 0; i < limit; i++, var = (var << 1) | 1) { \
EXPECT_EQ(i, fn(var)); \
} \
} \
{ \
/* Test the powers of 2 and powers + 1*/ \
type var = 1; \
for (int i = 0; i < limit; i++, var <<= 1) { \
EXPECT_EQ(i, fn(var)); \
EXPECT_EQ(i, fn(var | 1)); \
} \
} \
}

TEST(globalDefinitions, log2) {
EXPECT_EQ_LOG2(log2_intptr, uintptr_t);
EXPECT_EQ_LOG2(log2_intptr, intptr_t);
EXPECT_EQ_LOG2(log2_long, julong);
EXPECT_EQ_LOG2(log2_int, int);
EXPECT_EQ_LOG2(log2_jint, jint);
EXPECT_EQ_LOG2(log2_uint, uint);
EXPECT_EQ_LOG2(log2_jlong, jlong);
}

0 comments on commit 1953612

Please sign in to comment.