Insert random noops to increase security against ROP attacks (llvm)
[oota-llvm.git] / include / llvm / Support / RandomNumberGenerator.h
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
16 #ifndef LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
17 #define LLVM_SUPPORT_RANDOMNUMBERGENERATOR_H_
18
19 #include "llvm/ADT/StringRef.h"
20 #include "llvm/Support/Compiler.h"
21 #include "llvm/Support/DataTypes.h" // Needed for uint64_t on Windows.
22 #include <random>
23
24 namespace llvm {
25
26 /// A random number generator.
27 ///
28 /// Instances of this class should not be shared across threads. The
29 /// seed should be set by passing the -rng-seed=<uint64> option. Use
30 /// Module::createRNG to create a new RNG instance for use with that
31 /// module.
32 class RandomNumberGenerator {
33 public:
34   typedef std::mt19937_64 RNG;
35   typedef RNG::result_type result_type;
36
37   /// Returns a random number in the range [0, Max).
38   result_type operator()();
39
40   // Must define min and max to be compatible with URNG as used by
41   // std::uniform_*_distribution
42   static LLVM_CONSTEXPR result_type min() {
43     return RNG::min();
44   }
45   static LLVM_CONSTEXPR result_type max() {
46     return RNG::max();
47   }
48
49 private:
50   /// Seeds and salts the underlying RNG engine.
51   ///
52   /// This constructor should not be used directly. Instead use
53   /// Module::createRNG to create a new RNG salted with the Module ID.
54   RandomNumberGenerator(StringRef Salt);
55
56   // 64-bit Mersenne Twister by Matsumoto and Nishimura, 2000
57   // http://en.cppreference.com/w/cpp/numeric/random/mersenne_twister_engine
58   // This RNG is deterministically portable across C++11
59   // implementations.
60   RNG Generator;
61
62   // Noncopyable.
63   RandomNumberGenerator(const RandomNumberGenerator &other)
64       LLVM_DELETED_FUNCTION;
65   RandomNumberGenerator &
66   operator=(const RandomNumberGenerator &other) LLVM_DELETED_FUNCTION;
67
68   friend class Module;
69 };
70 }
71
72 #endif