blob: ed3467ba81df2f0c828a35126bf8f472b8fe5d74 [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
14#include <time.h>
15
16#include "llvm/Support/CommandLine.h"
17
18#include "IceRNG.h"
19
20namespace Ice {
21
22namespace {
23namespace cl = llvm::cl;
24
Jim Stichnoth33246422014-11-24 14:36:23 -080025// TODO(stichnot): See if we can easily use LLVM's -rng-seed option
26// and implementation. I expect the implementation is different and
27// therefore the tests would need to be changed.
Matt Wala1bd2fce2014-08-08 14:02:09 -070028cl::opt<unsigned long long>
Jim Stichnoth33246422014-11-24 14:36:23 -080029RandomSeed("sz-seed", cl::desc("Seed the random number generator"),
Matt Wala1bd2fce2014-08-08 14:02:09 -070030 cl::init(time(0)));
31
Matt Walac3302742014-08-15 16:21:56 -070032const unsigned MAX = 2147483647;
33
Matt Wala1bd2fce2014-08-08 14:02:09 -070034} // end of anonymous namespace
35
36// TODO(wala,stichnot): Switch to RNG implementation from LLVM or C++11.
37//
38// TODO(wala,stichnot): Make it possible to replay the RNG sequence in a
39// subsequent run, for reproducing a bug. Print the seed in a comment
40// in the asm output. Embed the seed in the binary via metadata that an
41// attacker can't introspect.
42RandomNumberGenerator::RandomNumberGenerator(llvm::StringRef)
43 : State(RandomSeed) {}
44
45uint64_t RandomNumberGenerator::next(uint64_t Max) {
46 // Lewis, Goodman, and Miller (1969)
Matt Walac3302742014-08-15 16:21:56 -070047 State = (16807 * State) % MAX;
Matt Wala1bd2fce2014-08-08 14:02:09 -070048 return State % Max;
49}
50
Matt Walac3302742014-08-15 16:21:56 -070051bool RandomNumberGeneratorWrapper::getTrueWithProbability(float Probability) {
52 return RNG.next(MAX) < Probability * MAX;
53}
54
Matt Wala1bd2fce2014-08-08 14:02:09 -070055} // end of namespace Ice