2
0

RandomNumberGenerator.cpp 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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 deterministic random number generation (RNG).
  11. // The current implementation is NOT cryptographically secure as it uses
  12. // the C++11 <random> facilities.
  13. //
  14. //===----------------------------------------------------------------------===//
  15. #include "llvm/Support/RandomNumberGenerator.h"
  16. #include "llvm/Support/CommandLine.h"
  17. #include "llvm/Support/Debug.h"
  18. #include "llvm/Support/raw_ostream.h"
  19. using namespace llvm;
  20. #define DEBUG_TYPE "rng"
  21. // Tracking BUG: 19665
  22. // http://llvm.org/bugs/show_bug.cgi?id=19665
  23. //
  24. // Do not change to cl::opt<uint64_t> since this silently breaks argument parsing.
  25. #if 0 // HLSL Change Starts - option pending
  26. static cl::opt<unsigned long long>
  27. Seed("rng-seed", cl::value_desc("seed"),
  28. cl::desc("Seed for the random number generator"), cl::init(0));
  29. #else
  30. static const unsigned long long Seed = 0; // will go boom in the constructor, can't be set yet
  31. #endif // HLSL Change Ends
  32. RandomNumberGenerator::RandomNumberGenerator(StringRef Salt) {
  33. DEBUG(
  34. if (Seed == 0)
  35. dbgs() << "Warning! Using unseeded random number generator.\n"
  36. );
  37. // Combine seed and salts using std::seed_seq.
  38. // Data: Seed-low, Seed-high, Salt
  39. // Note: std::seed_seq can only store 32-bit values, even though we
  40. // are using a 64-bit RNG. This isn't a problem since the Mersenne
  41. // twister constructor copies these correctly into its initial state.
  42. std::vector<uint32_t> Data;
  43. Data.reserve(2 + Salt.size());
  44. Data.push_back(Seed);
  45. Data.push_back(Seed >> 32);
  46. std::copy(Salt.begin(), Salt.end(), Data.end());
  47. std::seed_seq SeedSeq(Data.begin(), Data.end());
  48. Generator.seed(SeedSeq);
  49. }
  50. uint_fast64_t RandomNumberGenerator::operator()() {
  51. return Generator();
  52. }