summaryrefslogtreecommitdiff
path: root/libc/src/stdlib/rand.cpp
diff options
context:
space:
mode:
authorJoseph Huber <35342157+jhuber6@users.noreply.github.com>2023-10-19 17:01:43 -0400
committerGitHub <noreply@github.com>2023-10-19 17:01:43 -0400
commit630037ede4cec8870764bed27c1289388ac33097 (patch)
tree36ddca7d6c0e42e2aa6f2bba494e8f4f950cfbdb /libc/src/stdlib/rand.cpp
parenta39215768b58bb39716820959cedf82c76648770 (diff)
[libc] Partially implement 'rand' for the GPU (#66167)
Summary: This patch partially implements the `rand` function on the GPU. This is partial because the GPU currently doesn't support thread local storage or static initializers. To implement this on the GPU. I use 1/8th of the local / shared memory quota to treak the shared memory as thread local storage. This is done by simply allocating enough storage for each thread in the block and indexing into this based off of the thread id. The downside to this is that it does not initialize `srand` correctly to be `1` as the standard says, it is also wasteful. In the future we should figure out a way to support TLS on the GPU so that this can be completely common and less resource intensive.
Diffstat (limited to 'libc/src/stdlib/rand.cpp')
-rw-r--r--libc/src/stdlib/rand.cpp10
1 files changed, 6 insertions, 4 deletions
diff --git a/libc/src/stdlib/rand.cpp b/libc/src/stdlib/rand.cpp
index c5737a8b8454..ad543b4048a9 100644
--- a/libc/src/stdlib/rand.cpp
+++ b/libc/src/stdlib/rand.cpp
@@ -15,10 +15,12 @@ namespace LIBC_NAMESPACE {
// 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)) {
- rand_next ^= rand_next >> 12;
- rand_next ^= rand_next << 25;
- rand_next ^= rand_next >> 27;
- return static_cast<int>((rand_next * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
+ unsigned long x = rand_next;
+ x ^= x >> 12;
+ x ^= x << 25;
+ x ^= x >> 27;
+ rand_next = x;
+ return static_cast<int>((x * 0x2545F4914F6CDD1Dul) >> 32) & RAND_MAX;
}
} // namespace LIBC_NAMESPACE