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