Skip to content

[libc] Change rand implementation so all tests pass in both 32- and 64-bit systems #98692

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jul 17, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 30 additions & 11 deletions libc/src/stdlib/rand.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -14,20 +14,39 @@

namespace LIBC_NAMESPACE_DECL {

// An implementation of the xorshift64star pseudo random number generator. This
// is a good general purpose generator for most non-cryptographics applications.
LLVM_LIBC_FUNCTION(int, rand, (void)) {
unsigned long orig = rand_next.load(cpp::MemoryOrder::RELAXED);
for (;;) {
unsigned long x = orig;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
cpp::MemoryOrder::RELAXED))
return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
sleep_briefly();

// An implementation of the xorshift64star pseudo random number generator.
// This is a good general purpose generator for most non-cryptographics
// applications.
if constexpr (sizeof(void *) == sizeof(uint64_t)) {
for (;;) {
unsigned long x = orig;
x ^= x >> 12;
x ^= x << 25;
x ^= x >> 27;
if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
cpp::MemoryOrder::RELAXED))
return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
sleep_briefly();
}
} else {
// This is the xorshift32 pseudo random number generator, slightly different
// from the 64-bit star version above, as the previous version fails to
// generate uniform enough LSB in 32-bit systems.
for (;;) {
unsigned long x = orig;
x ^= x >> 13;
x ^= x << 27;
x ^= x >> 5;
if (rand_next.compare_exchange_strong(orig, x, cpp::MemoryOrder::ACQUIRE,
cpp::MemoryOrder::RELAXED))
return static_cast<int>(x * 1597334677ul) & RAND_MAX;
sleep_briefly();
}
}
__builtin_unreachable();
}

} // namespace LIBC_NAMESPACE_DECL
Loading