Use rand_r() instead of non-reentrant thread-unsafe rand() in GetRandomNumber()

Dear all,

In our LLVM-based compiler pipeline a major part of code generation is taken into application runtime. One side-effect of this organization is a need to be very careful about using code that might diverge application state. And we found that simple generation of temporary files over LLVM APIs introduces random noise into the program result. There reason is that LLVM’s GetRandomNumber call uses rand(), that clashes with rand() used in application. Taking in account that many client applications developers may be not aware of this at all [and just complain to us, that our compiler is bad because their program is now wrong], we propose switching to self- state maintaining rand() on LLVM side. Attached patch simply replaces the calls to srand() and rand() with a call to rand_r(), which uses static unsigned x value to keep its state locally.


  • D.

llvm.rand.patch (401 Bytes)

If we’re keeping the state locally now, perhaps we should store it in a per-thread variable. I know rand() isn’t thread safe to begin with, but it seems like rand_r() can be since it should keep no external state.

Agreed, done.

One thing I’m not sure about is this statement in docs:

POSIX.1-2008 marks rand_r() as obsolete.

  • And… what is the replacement?

2012/12/1 Justin Holewinski <>

llvm.rand.patch (410 Bytes)

Correcting my patch, reg. __thread stuff I’m not very familiar with.

  • D.

2012/12/1 Dmitry Mikushin <>

llvm.rand.patch (416 Bytes)

I don’t know if __thread is well-supported enough on compilers to use in LLVM core code. LLVM has its own support class: ThreadLocal

And if randr_r() is obsolete, I’m not sure we should be using it. What platforms have you tested this on? Is it available on Windows, Mac, BSDs? If not touching global state is important enough, perhaps we should add a (simple) random number generator to the Support library. I don’t think LLVM would require anything fancy.

We could use nrand48 for example, if it's available.