RandomNumberGenerator.cpp 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152
  1. //===-- RandomNumberGenerator.cpp - Implement RNG class -------------------===//
  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 implements random number generation (RNG).
  11. // The current implementation is NOT cryptographically secure as it uses
  12. // the C++11 <random> facilities.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #define DEBUG_TYPE "rng"
  16. #include "llvm/Support/RandomNumberGenerator.h"
  17. #include "llvm/Support/CommandLine.h"
  18. #include "llvm/Support/Debug.h"
  19. using namespace llvm;
  20. // Tracking BUG: 19665
  21. // http://llvm.org/bugs/show_bug.cgi?id=19665
  22. //
  23. // Do not change to cl::opt<uint64_t> since this silently breaks argument parsing.
  24. static cl::opt<unsigned long long>
  25. Seed("rng-seed", cl::value_desc("seed"),
  26. cl::desc("Seed for the random number generator"), cl::init(0));
  27. RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) {
  28. DEBUG(
  29. if (Seed == 0)
  30. errs() << "Warning! Using unseeded random number generator.\n"
  31. );
  32. // Combine seed and salt using std::seed_seq.
  33. // Entropy: Seed-low, Seed-high, Salt...
  34. size_t Size = Salt.size() + 2;
  35. uint32_t Data[Size];
  36. Data[0] = Seed;
  37. Data[1] = Seed >> 32;
  38. std::copy_n(Salt.begin(), Salt.size(), Data + 2);
  39. std::seed_seq SeedSeq(Data, Data + Size);
  40. Generator.seed(SeedSeq);
  41. }
  42. uint64_t RandomNumberGenerator::next(uint64_t Max) {
  43. std::uniform_int_distribution<uint64_t> distribution(0, Max - 1);
  44. return distribution(Generator);
  45. }