Skip to content

Commit 9acec2f

Browse files
[libc] Change rand implementation so all tests pass in both 32- and 64-bit systems
This patch makes rand select different constants depending on the arch. This is needed to avoid a test failure in 32-bit systems where the LSB of rand was not uniform enough when the 64-bit constants are used in 32-bit systems.
1 parent dd44003 commit 9acec2f

File tree

1 file changed

+19
-6
lines changed

1 file changed

+19
-6
lines changed

libc/src/stdlib/rand.cpp

Lines changed: 19 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -13,20 +13,33 @@
1313

1414
namespace LIBC_NAMESPACE {
1515

16-
// An implementation of the xorshift64star pseudo random number generator. This
16+
// An implementation of the xorshift* pseudo random number generator. This
1717
// is a good general purpose generator for most non-cryptographics applications.
18-
LLVM_LIBC_FUNCTION(int, rand, (void)) {
18+
static inline unsigned long xorshiftstar(unsigned long a, unsigned long b,
19+
unsigned long c, unsigned long d) {
1920
unsigned long orig = rand_next.load(cpp::MemoryOrder::RELAXED);
2021
for (;;) {
2122
unsigned long x = orig;
22-
x ^= x >> 12;
23-
x ^= x << 25;
24-
x ^= x >> 27;
23+
x ^= x >> a;
24+
x ^= x << b;
25+
x ^= x >> c;
2526
if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
2627
cpp::MemoryOrder::RELAXED))
27-
return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
28+
return x * d;
2829
sleep_briefly();
2930
}
3031
}
3132

33+
// An implementation of the xorshift64star pseudo random number generator. This
34+
// is a good general purpose generator for most non-cryptographics applications.
35+
LLVM_LIBC_FUNCTION(int, rand, (void)) {
36+
int res;
37+
if constexpr (sizeof(void *) == sizeof(uint64_t))
38+
res =
39+
static_cast<int>(xorshiftstar(12, 25, 27, 0x2545F4914F6CDD1Dul) >> 32);
40+
else
41+
res = static_cast<int>(xorshiftstar(13, 17, 5, 1597334677ul));
42+
return res & RAND_MAX;
43+
}
44+
3245
} // namespace LIBC_NAMESPACE

0 commit comments

Comments
 (0)