RandomNumberGenerator.h 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. //==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==//
  2. //
  3. // The LLVM Compiler Infrastructure
  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 defines an abstraction for deterministic random number
  11. // generation (RNG). Note that the current implementation is not
  12. // cryptographically secure as it uses the C++11 <random> facilities.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
  16. #define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
  17. #include "llvm/ADT/StringRef.h"
  18. #include "llvm/Support/Compiler.h"
  19. #include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows.
  20. #include <random>
  21. namespace llvm {
  22. /// A random number generator.
  23. ///
  24. /// Instances of this class should not be shared across threads. The
  25. /// seed should be set by passing the -rng-seed=<uint64> option. Use
  26. /// Module::createRNG to create a new RNG instance for use with that
  27. /// module.
  28. class RandomNumberGenerator {
  29. public:
  30. /// Returns a random number in the range [0, Max).
  31. uint_fast64_t operator()();
  32. private:
  33. /// Seeds and salts the underlying RNG engine.
  34. ///
  35. /// This constructor should not be used directly. Instead use
  36. /// Module::createRNG to create a new RNG salted with the Module ID.
  37. RandomNumberGenerator(StringRef Salt);
  38. // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000
  39. // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
  40. // This RNG is deterministically portable across C++11
  41. // implementations.
  42. std::mt19937_64 Generator;
  43. // Noncopyable.
  44. RandomNumberGenerator(const RandomNumberGenerator &other) = delete;
  45. RandomNumberGenerator &operator=(const RandomNumberGenerator &other) = delete;
  46. friend class Module;
  47. };
  48. }
  49. #endif