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