RandomNumberGenerator.h revision 288943
1107571Sgrehan//==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==//
2107571Sgrehan//
3107571Sgrehan//                     The LLVM Compiler Infrastructure
4107571Sgrehan//
5107571Sgrehan// This file is distributed under the University of Illinois Open Source
6107571Sgrehan// License. See LICENSE.TXT for details.
7107571Sgrehan//
8107571Sgrehan//===----------------------------------------------------------------------===//
9107571Sgrehan//
10107571Sgrehan// This file defines an abstraction for deterministic random number
11107571Sgrehan// generation (RNG).  Note that the current implementation is not
12107571Sgrehan// cryptographically secure as it uses the C++11 <random> facilities.
13107571Sgrehan//
14107571Sgrehan//===----------------------------------------------------------------------===//
15107571Sgrehan
16107571Sgrehan#ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
17107571Sgrehan#define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
18107571Sgrehan
19107571Sgrehan#include "llvm/ADT/StringRef.h"
20107571Sgrehan#include "llvm/Support/Compiler.h"
21107571Sgrehan#include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows.
22107571Sgrehan#include <random>
23107571Sgrehan
24107571Sgrehannamespace llvm {
25107571Sgrehan
26107571Sgrehan/// A random number generator.
27107571Sgrehan///
28107571Sgrehan/// Instances of this class should not be shared across threads. The
29107571Sgrehan/// seed should be set by passing the -rng-seed=<uint64> option. Use
30107571Sgrehan/// Module::createRNG to create a new RNG instance for use with that
31107571Sgrehan/// module.
32107571Sgrehanclass RandomNumberGenerator {
33107571Sgrehanpublic:
34107571Sgrehan  /// Returns a random number in the range [0, Max).
35107571Sgrehan  uint_fast64_t operator()();
36107571Sgrehan
37107571Sgrehanprivate:
38107571Sgrehan  /// Seeds and salts the underlying RNG engine.
39107571Sgrehan  ///
40107571Sgrehan  /// This constructor should not be used directly. Instead use
41107571Sgrehan  /// Module::createRNG to create a new RNG salted with the Module ID.
42107571Sgrehan  RandomNumberGenerator(StringRef Salt);
43107571Sgrehan
44217398Skib  // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000
45217398Skib  // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
46  // This RNG is deterministically portable across C++11
47  // implementations.
48  std::mt19937_64 Generator;
49
50  // Noncopyable.
51  RandomNumberGenerator(const RandomNumberGenerator &other) = delete;
52  RandomNumberGenerator &operator=(const RandomNumberGenerator &other) = delete;
53
54  friend class Module;
55};
56}
57
58#endif
59