Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 1 | //===- subzero/src/IceRNG.cpp - PRNG implementation -----------------------===// |
| 2 | // |
| 3 | // The Subzero Code Generator |
| 4 | // |
| 5 | // This file is distributed under the University of Illinois Open Source |
| 6 | // License. See LICENSE.TXT for details. |
| 7 | // |
| 8 | //===----------------------------------------------------------------------===// |
| 9 | // |
| 10 | // This file implements the random number generator. |
| 11 | // |
| 12 | //===----------------------------------------------------------------------===// |
| 13 | |
Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 14 | #include "IceRNG.h" |
| 15 | |
John Porto | 67f8de9 | 2015-06-25 10:14:17 -0700 | [diff] [blame] | 16 | #include <time.h> |
| 17 | |
Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 18 | namespace Ice { |
| 19 | |
| 20 | namespace { |
John Porto | 67f8de9 | 2015-06-25 10:14:17 -0700 | [diff] [blame] | 21 | constexpr unsigned MAX = 2147483647; |
Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 22 | } // end of anonymous namespace |
| 23 | |
| 24 | // TODO(wala,stichnot): Switch to RNG implementation from LLVM or C++11. |
| 25 | // |
| 26 | // TODO(wala,stichnot): Make it possible to replay the RNG sequence in a |
| 27 | // subsequent run, for reproducing a bug. Print the seed in a comment |
| 28 | // in the asm output. Embed the seed in the binary via metadata that an |
| 29 | // attacker can't introspect. |
Jan Voung | 1f47ad0 | 2015-03-20 15:01:26 -0700 | [diff] [blame] | 30 | RandomNumberGenerator::RandomNumberGenerator(uint64_t Seed, llvm::StringRef) |
| 31 | : State(Seed) {} |
Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 32 | |
| 33 | uint64_t RandomNumberGenerator::next(uint64_t Max) { |
| 34 | // Lewis, Goodman, and Miller (1969) |
Matt Wala | c330274 | 2014-08-15 16:21:56 -0700 | [diff] [blame] | 35 | State = (16807 * State) % MAX; |
Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 36 | return State % Max; |
| 37 | } |
| 38 | |
Matt Wala | c330274 | 2014-08-15 16:21:56 -0700 | [diff] [blame] | 39 | bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) { |
| 40 | return RNG.next(MAX) < Probability * MAX; |
| 41 | } |
| 42 | |
Matt Wala | 1bd2fce | 2014-08-08 14:02:09 -0700 | [diff] [blame] | 43 | } // end of namespace Ice |