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