blob: e3fa8c5468607d3238b817d44d155c34552bfbb2 [file] [log] [blame]
Matt Wala1bd2fce2014-08-08 14:02:09 -07001//===- 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 Wala1bd2fce2014-08-08 14:02:09 -070014#include "IceRNG.h"
15
John Porto67f8de92015-06-25 10:14:17 -070016#include <time.h>
17
Matt Wala1bd2fce2014-08-08 14:02:09 -070018namespace Ice {
19
20namespace {
John Porto67f8de92015-06-25 10:14:17 -070021constexpr unsigned MAX = 2147483647;
Matt Wala1bd2fce2014-08-08 14:02:09 -070022} // 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 Voung1f47ad02015-03-20 15:01:26 -070030RandomNumberGenerator::RandomNumberGenerator(uint64_t Seed, llvm::StringRef)
31 : State(Seed) {}
Matt Wala1bd2fce2014-08-08 14:02:09 -070032
33uint64_t RandomNumberGenerator::next(uint64_t Max) {
34 // Lewis, Goodman, and Miller (1969)
Matt Walac3302742014-08-15 16:21:56 -070035 State = (16807 * State) % MAX;
Matt Wala1bd2fce2014-08-08 14:02:09 -070036 return State % Max;
37}
38
Matt Walac3302742014-08-15 16:21:56 -070039bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) {
40 return RNG.next(MAX) < Probability * MAX;
41}
42
Matt Wala1bd2fce2014-08-08 14:02:09 -070043} // end of namespace Ice