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