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