LLVM  4.0.0
ValueMap.h
Go to the documentation of this file.
1 //===- ValueMap.h - Safe map from Values to data ----------------*- 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 the ValueMap class. ValueMap maps Value* or any subclass
11 // to an arbitrary other type. It provides the DenseMap interface but updates
12 // itself to remain safe when keys are RAUWed or deleted. By default, when a
13 // key is RAUWed from V1 to V2, the old mapping V1->target is removed, and a new
14 // mapping V2->target is added. If V2 already existed, its old target is
15 // overwritten. When a key is deleted, its mapping is removed.
16 //
17 // You can override a ValueMap's Config parameter to control exactly what
18 // happens on RAUW and destruction and to get called back on each event. It's
19 // legal to call back into the ValueMap from a Config's callbacks. Config
20 // parameters should inherit from ValueMapConfig<KeyT> to get default
21 // implementations of all the methods ValueMap uses. See ValueMapConfig for
22 // documentation of the functions you can override.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #ifndef LLVM_IR_VALUEMAP_H
27 #define LLVM_IR_VALUEMAP_H
28 
29 #include "llvm/ADT/DenseMap.h"
30 #include "llvm/ADT/DenseMapInfo.h"
31 #include "llvm/ADT/None.h"
32 #include "llvm/ADT/Optional.h"
33 #include "llvm/IR/TrackingMDRef.h"
34 #include "llvm/IR/ValueHandle.h"
35 #include "llvm/Support/Casting.h"
36 #include "llvm/Support/Mutex.h"
38 #include <algorithm>
39 #include <cassert>
40 #include <cstddef>
41 #include <iterator>
42 #include <type_traits>
43 #include <utility>
44 
45 namespace llvm {
46 
47 template<typename KeyT, typename ValueT, typename Config>
49 
50 template<typename DenseMapT, typename KeyT>
52 template<typename DenseMapT, typename KeyT>
54 
55 /// This class defines the default behavior for configurable aspects of
56 /// ValueMap<>. User Configs should inherit from this class to be as compatible
57 /// as possible with future versions of ValueMap.
58 template<typename KeyT, typename MutexT = sys::Mutex>
60  typedef MutexT mutex_type;
61 
62  /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
63  /// false, the ValueMap will leave the original mapping in place.
64  enum { FollowRAUW = true };
65 
66  // All methods will be called with a first argument of type ExtraData. The
67  // default implementations in this class take a templated first argument so
68  // that users' subclasses can use any type they want without having to
69  // override all the defaults.
70  struct ExtraData {};
71 
72  template<typename ExtraDataT>
73  static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {}
74  template<typename ExtraDataT>
75  static void onDelete(const ExtraDataT &/*Data*/, KeyT /*Old*/) {}
76 
77  /// Returns a mutex that should be acquired around any changes to the map.
78  /// This is only acquired from the CallbackVH (and held around calls to onRAUW
79  /// and onDelete) and not inside other ValueMap methods. NULL means that no
80  /// mutex is necessary.
81  template<typename ExtraDataT>
82  static mutex_type *getMutex(const ExtraDataT &/*Data*/) { return nullptr; }
83 };
84 
85 /// See the file comment.
86 template<typename KeyT, typename ValueT, typename Config =ValueMapConfig<KeyT>>
87 class ValueMap {
88  friend class ValueMapCallbackVH<KeyT, ValueT, Config>;
89 
93  typedef typename Config::ExtraData ExtraData;
94  MapT Map;
95  Optional<MDMapT> MDMap;
96  ExtraData Data;
97 
98  bool MayMapMetadata = true;
99 
100 public:
101  typedef KeyT key_type;
103  typedef std::pair<KeyT, ValueT> value_type;
104  typedef unsigned size_type;
105 
106  explicit ValueMap(unsigned NumInitBuckets = 64)
107  : Map(NumInitBuckets), Data() {}
108  explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
109  : Map(NumInitBuckets), Data(Data) {}
110  ValueMap(const ValueMap &) = delete;
111  ValueMap &operator=(const ValueMap &) = delete;
112 
113  bool hasMD() const { return bool(MDMap); }
114  MDMapT &MD() {
115  if (!MDMap)
116  MDMap.emplace();
117  return *MDMap;
118  }
119  Optional<MDMapT> &getMDMap() { return MDMap; }
120 
121  bool mayMapMetadata() const { return MayMapMetadata; }
122  void enableMapMetadata() { MayMapMetadata = true; }
123  void disableMapMetadata() { MayMapMetadata = false; }
124 
125  /// Get the mapped metadata, if it's in the map.
127  if (!MDMap)
128  return None;
129  auto Where = MDMap->find(MD);
130  if (Where == MDMap->end())
131  return None;
132  return Where->second.get();
133  }
134 
137  inline iterator begin() { return iterator(Map.begin()); }
138  inline iterator end() { return iterator(Map.end()); }
139  inline const_iterator begin() const { return const_iterator(Map.begin()); }
140  inline const_iterator end() const { return const_iterator(Map.end()); }
141 
142  bool empty() const { return Map.empty(); }
143  size_type size() const { return Map.size(); }
144 
145  /// Grow the map so that it has at least Size buckets. Does not shrink
146  void resize(size_t Size) { Map.resize(Size); }
147 
148  void clear() {
149  Map.clear();
150  MDMap.reset();
151  }
152 
153  /// Return 1 if the specified key is in the map, 0 otherwise.
154  size_type count(const KeyT &Val) const {
155  return Map.find_as(Val) == Map.end() ? 0 : 1;
156  }
157 
158  iterator find(const KeyT &Val) {
159  return iterator(Map.find_as(Val));
160  }
161  const_iterator find(const KeyT &Val) const {
162  return const_iterator(Map.find_as(Val));
163  }
164 
165  /// lookup - Return the entry for the specified key, or a default
166  /// constructed value if no such entry exists.
167  ValueT lookup(const KeyT &Val) const {
168  typename MapT::const_iterator I = Map.find_as(Val);
169  return I != Map.end() ? I->second : ValueT();
170  }
171 
172  // Inserts key,value pair into the map if the key isn't already in the map.
173  // If the key is already in the map, it returns false and doesn't update the
174  // value.
175  std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
176  auto MapResult = Map.insert(std::make_pair(Wrap(KV.first), KV.second));
177  return std::make_pair(iterator(MapResult.first), MapResult.second);
178  }
179 
180  std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
181  auto MapResult =
182  Map.insert(std::make_pair(Wrap(KV.first), std::move(KV.second)));
183  return std::make_pair(iterator(MapResult.first), MapResult.second);
184  }
185 
186  /// insert - Range insertion of pairs.
187  template<typename InputIt>
188  void insert(InputIt I, InputIt E) {
189  for (; I != E; ++I)
190  insert(*I);
191  }
192 
193  bool erase(const KeyT &Val) {
194  typename MapT::iterator I = Map.find_as(Val);
195  if (I == Map.end())
196  return false;
197 
198  Map.erase(I);
199  return true;
200  }
201  void erase(iterator I) {
202  return Map.erase(I.base());
203  }
204 
205  value_type& FindAndConstruct(const KeyT &Key) {
206  return Map.FindAndConstruct(Wrap(Key));
207  }
208 
209  ValueT &operator[](const KeyT &Key) {
210  return Map[Wrap(Key)];
211  }
212 
213  /// isPointerIntoBucketsArray - Return true if the specified pointer points
214  /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
215  /// value in the ValueMap).
216  bool isPointerIntoBucketsArray(const void *Ptr) const {
217  return Map.isPointerIntoBucketsArray(Ptr);
218  }
219 
220  /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
221  /// array. In conjunction with the previous method, this can be used to
222  /// determine whether an insertion caused the ValueMap to reallocate.
223  const void *getPointerIntoBucketsArray() const {
224  return Map.getPointerIntoBucketsArray();
225  }
226 
227 private:
228  // Takes a key being looked up in the map and wraps it into a
229  // ValueMapCallbackVH, the actual key type of the map. We use a helper
230  // function because ValueMapCVH is constructed with a second parameter.
231  ValueMapCVH Wrap(KeyT key) const {
232  // The only way the resulting CallbackVH could try to modify *this (making
233  // the const_cast incorrect) is if it gets inserted into the map. But then
234  // this function must have been called from a non-const method, making the
235  // const_cast ok.
236  return ValueMapCVH(key, const_cast<ValueMap*>(this));
237  }
238 };
239 
240 // This CallbackVH updates its ValueMap when the contained Value changes,
241 // according to the user's preferences expressed through the Config object.
242 template <typename KeyT, typename ValueT, typename Config>
243 class ValueMapCallbackVH final : public CallbackVH {
244  friend class ValueMap<KeyT, ValueT, Config>;
246 
248  typedef typename std::remove_pointer<KeyT>::type KeySansPointerT;
249 
250  ValueMapT *Map;
251 
252  ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
253  : CallbackVH(const_cast<Value*>(static_cast<const Value*>(Key))),
254  Map(Map) {}
255 
256  // Private constructor used to create empty/tombstone DenseMap keys.
257  ValueMapCallbackVH(Value *V) : CallbackVH(V), Map(nullptr) {}
258 
259 public:
260  KeyT Unwrap() const { return cast_or_null<KeySansPointerT>(getValPtr()); }
261 
262  void deleted() override {
263  // Make a copy that won't get changed even when *this is destroyed.
264  ValueMapCallbackVH Copy(*this);
265  typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
267  if (M)
269  Config::onDelete(Copy.Map->Data, Copy.Unwrap()); // May destroy *this.
270  Copy.Map->Map.erase(Copy); // Definitely destroys *this.
271  }
272 
273  void allUsesReplacedWith(Value *new_key) override {
274  assert(isa<KeySansPointerT>(new_key) &&
275  "Invalid RAUW on key of ValueMap<>");
276  // Make a copy that won't get changed even when *this is destroyed.
277  ValueMapCallbackVH Copy(*this);
278  typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
280  if (M)
282 
283  KeyT typed_new_key = cast<KeySansPointerT>(new_key);
284  // Can destroy *this:
285  Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
286  if (Config::FollowRAUW) {
287  typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
288  // I could == Copy.Map->Map.end() if the onRAUW callback already
289  // removed the old mapping.
290  if (I != Copy.Map->Map.end()) {
291  ValueT Target(std::move(I->second));
292  Copy.Map->Map.erase(I); // Definitely destroys *this.
293  Copy.Map->insert(std::make_pair(typed_new_key, std::move(Target)));
294  }
295  }
296  }
297 };
298 
299 template<typename KeyT, typename ValueT, typename Config>
300 struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config>> {
302 
303  static inline VH getEmptyKey() {
305  }
306 
307  static inline VH getTombstoneKey() {
309  }
310 
311  static unsigned getHashValue(const VH &Val) {
313  }
314 
315  static unsigned getHashValue(const KeyT &Val) {
317  }
318 
319  static bool isEqual(const VH &LHS, const VH &RHS) {
320  return LHS == RHS;
321  }
322 
323  static bool isEqual(const KeyT &LHS, const VH &RHS) {
324  return LHS == RHS.getValPtr();
325  }
326 };
327 
328 template<typename DenseMapT, typename KeyT>
329 class ValueMapIterator :
330  public std::iterator<std::forward_iterator_tag,
331  std::pair<KeyT, typename DenseMapT::mapped_type>,
332  ptrdiff_t> {
333  typedef typename DenseMapT::iterator BaseT;
334  typedef typename DenseMapT::mapped_type ValueT;
335 
336  BaseT I;
337 
338 public:
339  ValueMapIterator() : I() {}
340  ValueMapIterator(BaseT I) : I(I) {}
341 
342  BaseT base() const { return I; }
343 
344  struct ValueTypeProxy {
345  const KeyT first;
346  ValueT& second;
347  ValueTypeProxy *operator->() { return this; }
348  operator std::pair<KeyT, ValueT>() const {
349  return std::make_pair(first, second);
350  }
351  };
352 
354  ValueTypeProxy Result = {I->first.Unwrap(), I->second};
355  return Result;
356  }
357 
359  return operator*();
360  }
361 
362  bool operator==(const ValueMapIterator &RHS) const {
363  return I == RHS.I;
364  }
365  bool operator!=(const ValueMapIterator &RHS) const {
366  return I != RHS.I;
367  }
368 
369  inline ValueMapIterator& operator++() { // Preincrement
370  ++I;
371  return *this;
372  }
373  ValueMapIterator operator++(int) { // Postincrement
374  ValueMapIterator tmp = *this; ++*this; return tmp;
375  }
376 };
377 
378 template<typename DenseMapT, typename KeyT>
379 class ValueMapConstIterator :
380  public std::iterator<std::forward_iterator_tag,
381  std::pair<KeyT, typename DenseMapT::mapped_type>,
382  ptrdiff_t> {
383  typedef typename DenseMapT::const_iterator BaseT;
384  typedef typename DenseMapT::mapped_type ValueT;
385 
386  BaseT I;
387 
388 public:
390  ValueMapConstIterator(BaseT I) : I(I) {}
392  : I(Other.base()) {}
393 
394  BaseT base() const { return I; }
395 
396  struct ValueTypeProxy {
397  const KeyT first;
398  const ValueT& second;
399  ValueTypeProxy *operator->() { return this; }
400  operator std::pair<KeyT, ValueT>() const {
401  return std::make_pair(first, second);
402  }
403  };
404 
406  ValueTypeProxy Result = {I->first.Unwrap(), I->second};
407  return Result;
408  }
409 
411  return operator*();
412  }
413 
414  bool operator==(const ValueMapConstIterator &RHS) const {
415  return I == RHS.I;
416  }
417  bool operator!=(const ValueMapConstIterator &RHS) const {
418  return I != RHS.I;
419  }
420 
421  inline ValueMapConstIterator& operator++() { // Preincrement
422  ++I;
423  return *this;
424  }
425  ValueMapConstIterator operator++(int) { // Postincrement
426  ValueMapConstIterator tmp = *this; ++*this; return tmp;
427  }
428 };
429 
430 } // end namespace llvm
431 
432 #endif // LLVM_IR_VALUEMAP_H
void clear()
Definition: ValueMap.h:148
ValueTypeProxy operator->() const
Definition: ValueMap.h:358
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: ValueMap.h:175
const_iterator begin() const
Definition: ValueMap.h:139
static void onDelete(const ExtraDataT &, KeyT)
Definition: ValueMap.h:75
ValueT lookup(const KeyT &Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
Definition: ValueMap.h:167
size_type count(const KeyT &Val) const
Return 1 if the specified key is in the map, 0 otherwise.
Definition: ValueMap.h:154
Optional< Metadata * > getMappedMD(const Metadata *MD) const
Get the mapped metadata, if it's in the map.
Definition: ValueMap.h:126
This class defines the default behavior for configurable aspects of ValueMap<>.
Definition: ValueMap.h:59
std::pair< KeyT, ValueT > value_type
Definition: ValueMap.h:103
bool empty() const
Definition: ValueMap.h:142
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:172
ValueMap(unsigned NumInitBuckets=64)
Definition: ValueMap.h:106
BaseT base() const
Definition: ValueMap.h:342
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition: ValueMap.h:223
unsigned size_type
Definition: ValueMap.h:104
const void * getPointerIntoBucketsArray() const
getPointerIntoBucketsArray() - Return an opaque pointer into the buckets array.
Definition: DenseMap.h:296
ValueTypeProxy operator->() const
Definition: ValueMap.h:410
ValueMapConstIterator(ValueMapIterator< DenseMapT, KeyT > Other)
Definition: ValueMap.h:391
std::pair< iterator, bool > insert(std::pair< KeyT, ValueT > &&KV)
Definition: ValueMap.h:180
iterator find(const KeyT &Val)
Definition: ValueMap.h:158
void enableMapMetadata()
Definition: ValueMap.h:122
value_type & FindAndConstruct(const KeyT &Key)
Definition: ValueMap.h:205
size_type size() const
Definition: ValueMap.h:143
void allUsesReplacedWith(Value *new_key) override
Callback for Value RAUW.
Definition: ValueMap.h:273
ValueMapConstIterator< MapT, KeyT > const_iterator
Definition: ValueMap.h:136
static GCRegistry::Add< CoreCLRGC > E("coreclr","CoreCLR-compatible GC")
value_type & FindAndConstruct(const KeyT &Key)
Definition: DenseMap.h:262
ValueMap(const ExtraData &Data, unsigned NumInitBuckets=64)
Definition: ValueMap.h:108
bool erase(const KeyT &Val)
Definition: DenseMap.h:243
Value * getValPtr() const
Definition: ValueHandle.h:93
ValueMapIterator & operator++()
Definition: ValueMap.h:369
bool operator==(const ValueMapConstIterator &RHS) const
Definition: ValueMap.h:414
Optional< MDMapT > & getMDMap()
Definition: ValueMap.h:119
static bool isEqual(const VH &LHS, const VH &RHS)
Definition: ValueMap.h:319
A pared-down imitation of std::unique_lock from C++11.
Definition: UniqueLock.h:28
bool operator!=(const ValueMapIterator &RHS) const
Definition: ValueMap.h:365
static mutex_type * getMutex(const ExtraDataT &)
Returns a mutex that should be acquired around any changes to the map.
Definition: ValueMap.h:82
void disableMapMetadata()
Definition: ValueMap.h:123
ValueMapCallbackVH< KeyT, ValueT, Config > VH
Definition: ValueMap.h:301
ValueMapConstIterator operator++(int)
Definition: ValueMap.h:425
ValueMapIterator operator++(int)
Definition: ValueMap.h:373
bool mayMapMetadata() const
Definition: ValueMap.h:121
const_iterator end() const
Definition: ValueMap.h:140
iterator end()
Definition: ValueMap.h:138
void insert(InputIt I, InputIt E)
insert - Range insertion of pairs.
Definition: ValueMap.h:188
static void onRAUW(const ExtraDataT &, KeyT, KeyT)
Definition: ValueMap.h:73
See the file comment.
Definition: ValueMap.h:87
ValueT mapped_type
Definition: ValueMap.h:102
ValueMapIterator(BaseT I)
Definition: ValueMap.h:340
static const char * Target
ValueTypeProxy operator*() const
Definition: ValueMap.h:353
void erase(iterator I)
Definition: ValueMap.h:201
void resize(size_t Size)
Grow the map so that it has at least Size buckets. Does not shrink.
Definition: ValueMap.h:146
bool operator!=(const ValueMapConstIterator &RHS) const
Definition: ValueMap.h:417
const_iterator find(const KeyT &Val) const
Definition: ValueMap.h:161
bool hasMD() const
Definition: ValueMap.h:113
bool isPointerIntoBucketsArray(const void *Ptr) const
isPointerIntoBucketsArray - Return true if the specified pointer points somewhere into the DenseMap's...
Definition: DenseMap.h:289
unsigned size() const
Definition: DenseMap.h:83
ValueMapIterator< MapT, KeyT > iterator
Definition: ValueMap.h:135
iterator begin()
Definition: DenseMap.h:65
#define I(x, y, z)
Definition: MD5.cpp:54
iterator end()
Definition: DenseMap.h:69
static bool isEqual(const KeyT &LHS, const VH &RHS)
Definition: ValueMap.h:323
LLVM_NODISCARD bool empty() const
Definition: DenseMap.h:80
iterator find_as(const LookupKeyT &Val)
Alternate version of find() which allows a different, and possibly less expensive, key type.
Definition: DenseMap.h:146
bool isPointerIntoBucketsArray(const void *Ptr) const
isPointerIntoBucketsArray - Return true if the specified pointer points somewhere into the ValueMap's...
Definition: ValueMap.h:216
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
aarch64 promote const
LLVM Value Representation.
Definition: Value.h:71
bool operator==(const ValueMapIterator &RHS) const
Definition: ValueMap.h:362
ValueMap & operator=(const ValueMap &)=delete
ValueMapConstIterator & operator++()
Definition: ValueMap.h:421
Value handle with callbacks on RAUW and destruction.
Definition: ValueHandle.h:333
int * Ptr
ValueT & operator[](const KeyT &Key)
Definition: ValueMap.h:209
KeyT Unwrap() const
Definition: ValueMap.h:260
MDMapT & MD()
Definition: ValueMap.h:114
Root of the metadata hierarchy.
Definition: Metadata.h:55
void deleted() override
Callback for Value destruction.
Definition: ValueMap.h:262
iterator begin()
Definition: ValueMap.h:137
bool erase(const KeyT &Val)
Definition: ValueMap.h:193
ValueTypeProxy operator*() const
Definition: ValueMap.h:405