RandomNumberGenerator.h 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. //==- llvm/Support/RandomNumberGenerator.h - RNG for diversity ---*- C++ -*-==//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file defines an abstraction for deterministic random number
  10. // generation (RNG). Note that the current implementation is not
  11. // cryptographically secure as it uses the C++11 <random> facilities.
  12. //
  13. //===----------------------------------------------------------------------===//
  14. #ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
  15. #define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
  16. #include "llvm/Support/Compiler.h"
  17. #include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows.
  18. #include <random>
  19. #include <system_error>
  20. namespace llvm {
  21. class StringRef;
  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. // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000
  30. // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
  31. // This RNG is deterministically portable across C++11
  32. // implementations.
  33. using generator_type = std::mt19937_64;
  34. public:
  35. using result_type = generator_type::result_type;
  36. /// Returns a random number in the range [0, Max).
  37. result_type operator()();
  38. static constexpr result_type min() { return generator_type::min(); }
  39. static constexpr result_type max() { return generator_type::max(); }
  40. private:
  41. /// Seeds and salts the underlying RNG engine.
  42. ///
  43. /// This constructor should not be used directly. Instead use
  44. /// Module::createRNG to create a new RNG salted with the Module ID.
  45. RandomNumberGenerator(StringRef Salt);
  46. generator_type Generator;
  47. // Noncopyable.
  48. RandomNumberGenerator(const RandomNumberGenerator &other) = delete;
  49. RandomNumberGenerator &operator=(const RandomNumberGenerator &other) = delete;
  50. friend class Module;
  51. };
  52. // Get random vector of specified size
  53. std::error_code getRandomBytes(void *Buffer, size_t Size);
  54. }
  55. #endif