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