1 //===- ValueMap.h - Safe map from Values to data ----------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 // This file defines the ValueMap class. ValueMap maps Value* or any subclass
10 // to an arbitrary other type. It provides the DenseMap interface but updates
11 // itself to remain safe when keys are RAUWed or deleted. By default, when a
12 // key is RAUWed from V1 to V2, the old mapping V1->target is removed, and a new
13 // mapping V2->target is added. If V2 already existed, its old target is
14 // overwritten. When a key is deleted, its mapping is removed.
16 // You can override a ValueMap's Config parameter to control exactly what
17 // happens on RAUW and destruction and to get called back on each event. It's
18 // legal to call back into the ValueMap from a Config's callbacks. Config
19 // parameters should inherit from ValueMapConfig<KeyT> to get default
20 // implementations of all the methods ValueMap uses. See ValueMapConfig for
21 // documentation of the functions you can override.
23 //===----------------------------------------------------------------------===//
25 #ifndef LLVM_IR_VALUEMAP_H
26 #define LLVM_IR_VALUEMAP_H
28 #include "llvm/ADT/DenseMap.h"
29 #include "llvm/ADT/DenseMapInfo.h"
30 #include "llvm/ADT/None.h"
31 #include "llvm/ADT/Optional.h"
32 #include "llvm/IR/TrackingMDRef.h"
33 #include "llvm/IR/ValueHandle.h"
34 #include "llvm/Support/Casting.h"
35 #include "llvm/Support/Mutex.h"
41 #include <type_traits>
46 template<typename KeyT
, typename ValueT
, typename Config
>
47 class ValueMapCallbackVH
;
48 template<typename DenseMapT
, typename KeyT
>
49 class ValueMapIterator
;
50 template<typename DenseMapT
, typename KeyT
>
51 class ValueMapConstIterator
;
53 /// This class defines the default behavior for configurable aspects of
54 /// ValueMap<>. User Configs should inherit from this class to be as compatible
55 /// as possible with future versions of ValueMap.
56 template<typename KeyT
, typename MutexT
= sys::Mutex
>
57 struct ValueMapConfig
{
58 using mutex_type
= MutexT
;
60 /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
61 /// false, the ValueMap will leave the original mapping in place.
62 enum { FollowRAUW
= true };
64 // All methods will be called with a first argument of type ExtraData. The
65 // default implementations in this class take a templated first argument so
66 // that users' subclasses can use any type they want without having to
67 // override all the defaults.
70 template<typename ExtraDataT
>
71 static void onRAUW(const ExtraDataT
& /*Data*/, KeyT
/*Old*/, KeyT
/*New*/) {}
72 template<typename ExtraDataT
>
73 static void onDelete(const ExtraDataT
&/*Data*/, KeyT
/*Old*/) {}
75 /// Returns a mutex that should be acquired around any changes to the map.
76 /// This is only acquired from the CallbackVH (and held around calls to onRAUW
77 /// and onDelete) and not inside other ValueMap methods. NULL means that no
78 /// mutex is necessary.
79 template<typename ExtraDataT
>
80 static mutex_type
*getMutex(const ExtraDataT
&/*Data*/) { return nullptr; }
83 /// See the file comment.
84 template<typename KeyT
, typename ValueT
, typename Config
=ValueMapConfig
<KeyT
>>
86 friend class ValueMapCallbackVH
<KeyT
, ValueT
, Config
>;
88 using ValueMapCVH
= ValueMapCallbackVH
<KeyT
, ValueT
, Config
>;
89 using MapT
= DenseMap
<ValueMapCVH
, ValueT
, DenseMapInfo
<ValueMapCVH
>>;
90 using MDMapT
= DenseMap
<const Metadata
*, TrackingMDRef
>;
91 using ExtraData
= typename
Config::ExtraData
;
94 Optional
<MDMapT
> MDMap
;
98 using key_type
= KeyT
;
99 using mapped_type
= ValueT
;
100 using value_type
= std::pair
<KeyT
, ValueT
>;
101 using size_type
= unsigned;
103 explicit ValueMap(unsigned NumInitBuckets
= 64)
104 : Map(NumInitBuckets
), Data() {}
105 explicit ValueMap(const ExtraData
&Data
, unsigned NumInitBuckets
= 64)
106 : Map(NumInitBuckets
), Data(Data
) {}
107 // ValueMap can't be copied nor moved, beucase the callbacks store pointer
109 ValueMap(const ValueMap
&) = delete;
110 ValueMap(ValueMap
&&) = delete;
111 ValueMap
&operator=(const ValueMap
&) = delete;
112 ValueMap
&operator=(ValueMap
&&) = delete;
114 bool hasMD() const { return bool(MDMap
); }
120 Optional
<MDMapT
> &getMDMap() { return MDMap
; }
122 /// Get the mapped metadata, if it's in the map.
123 Optional
<Metadata
*> getMappedMD(const Metadata
*MD
) const {
126 auto Where
= MDMap
->find(MD
);
127 if (Where
== MDMap
->end())
129 return Where
->second
.get();
132 using iterator
= ValueMapIterator
<MapT
, KeyT
>;
133 using const_iterator
= ValueMapConstIterator
<MapT
, KeyT
>;
135 inline iterator
begin() { return iterator(Map
.begin()); }
136 inline iterator
end() { return iterator(Map
.end()); }
137 inline const_iterator
begin() const { return const_iterator(Map
.begin()); }
138 inline const_iterator
end() const { return const_iterator(Map
.end()); }
140 bool empty() const { return Map
.empty(); }
141 size_type
size() const { return Map
.size(); }
143 /// Grow the map so that it has at least Size buckets. Does not shrink
144 void resize(size_t Size
) { Map
.resize(Size
); }
151 /// Return 1 if the specified key is in the map, 0 otherwise.
152 size_type
count(const KeyT
&Val
) const {
153 return Map
.find_as(Val
) == Map
.end() ? 0 : 1;
156 iterator
find(const KeyT
&Val
) {
157 return iterator(Map
.find_as(Val
));
159 const_iterator
find(const KeyT
&Val
) const {
160 return const_iterator(Map
.find_as(Val
));
163 /// lookup - Return the entry for the specified key, or a default
164 /// constructed value if no such entry exists.
165 ValueT
lookup(const KeyT
&Val
) const {
166 typename
MapT::const_iterator I
= Map
.find_as(Val
);
167 return I
!= Map
.end() ? I
->second
: ValueT();
170 // Inserts key,value pair into the map if the key isn't already in the map.
171 // If the key is already in the map, it returns false and doesn't update the
173 std::pair
<iterator
, bool> insert(const std::pair
<KeyT
, ValueT
> &KV
) {
174 auto MapResult
= Map
.insert(std::make_pair(Wrap(KV
.first
), KV
.second
));
175 return std::make_pair(iterator(MapResult
.first
), MapResult
.second
);
178 std::pair
<iterator
, bool> insert(std::pair
<KeyT
, ValueT
> &&KV
) {
180 Map
.insert(std::make_pair(Wrap(KV
.first
), std::move(KV
.second
)));
181 return std::make_pair(iterator(MapResult
.first
), MapResult
.second
);
184 /// insert - Range insertion of pairs.
185 template<typename InputIt
>
186 void insert(InputIt I
, InputIt E
) {
191 bool erase(const KeyT
&Val
) {
192 typename
MapT::iterator I
= Map
.find_as(Val
);
199 void erase(iterator I
) {
200 return Map
.erase(I
.base());
203 value_type
& FindAndConstruct(const KeyT
&Key
) {
204 return Map
.FindAndConstruct(Wrap(Key
));
207 ValueT
&operator[](const KeyT
&Key
) {
208 return Map
[Wrap(Key
)];
211 /// isPointerIntoBucketsArray - Return true if the specified pointer points
212 /// somewhere into the ValueMap's array of buckets (i.e. either to a key or
213 /// value in the ValueMap).
214 bool isPointerIntoBucketsArray(const void *Ptr
) const {
215 return Map
.isPointerIntoBucketsArray(Ptr
);
218 /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
219 /// array. In conjunction with the previous method, this can be used to
220 /// determine whether an insertion caused the ValueMap to reallocate.
221 const void *getPointerIntoBucketsArray() const {
222 return Map
.getPointerIntoBucketsArray();
226 // Takes a key being looked up in the map and wraps it into a
227 // ValueMapCallbackVH, the actual key type of the map. We use a helper
228 // function because ValueMapCVH is constructed with a second parameter.
229 ValueMapCVH
Wrap(KeyT key
) const {
230 // The only way the resulting CallbackVH could try to modify *this (making
231 // the const_cast incorrect) is if it gets inserted into the map. But then
232 // this function must have been called from a non-const method, making the
234 return ValueMapCVH(key
, const_cast<ValueMap
*>(this));
238 // This CallbackVH updates its ValueMap when the contained Value changes,
239 // according to the user's preferences expressed through the Config object.
240 template <typename KeyT
, typename ValueT
, typename Config
>
241 class ValueMapCallbackVH final
: public CallbackVH
{
242 friend class ValueMap
<KeyT
, ValueT
, Config
>;
243 friend struct DenseMapInfo
<ValueMapCallbackVH
>;
245 using ValueMapT
= ValueMap
<KeyT
, ValueT
, Config
>;
246 using KeySansPointerT
= typename
std::remove_pointer
<KeyT
>::type
;
250 ValueMapCallbackVH(KeyT Key
, ValueMapT
*Map
)
251 : CallbackVH(const_cast<Value
*>(static_cast<const Value
*>(Key
))),
254 // Private constructor used to create empty/tombstone DenseMap keys.
255 ValueMapCallbackVH(Value
*V
) : CallbackVH(V
), Map(nullptr) {}
258 KeyT
Unwrap() const { return cast_or_null
<KeySansPointerT
>(getValPtr()); }
260 void deleted() override
{
261 // Make a copy that won't get changed even when *this is destroyed.
262 ValueMapCallbackVH
Copy(*this);
263 typename
Config::mutex_type
*M
= Config::getMutex(Copy
.Map
->Data
);
264 std::unique_lock
<typename
Config::mutex_type
> Guard
;
266 Guard
= std::unique_lock
<typename
Config::mutex_type
>(*M
);
267 Config::onDelete(Copy
.Map
->Data
, Copy
.Unwrap()); // May destroy *this.
268 Copy
.Map
->Map
.erase(Copy
); // Definitely destroys *this.
271 void allUsesReplacedWith(Value
*new_key
) override
{
272 assert(isa
<KeySansPointerT
>(new_key
) &&
273 "Invalid RAUW on key of ValueMap<>");
274 // Make a copy that won't get changed even when *this is destroyed.
275 ValueMapCallbackVH
Copy(*this);
276 typename
Config::mutex_type
*M
= Config::getMutex(Copy
.Map
->Data
);
277 std::unique_lock
<typename
Config::mutex_type
> Guard
;
279 Guard
= std::unique_lock
<typename
Config::mutex_type
>(*M
);
281 KeyT typed_new_key
= cast
<KeySansPointerT
>(new_key
);
282 // Can destroy *this:
283 Config::onRAUW(Copy
.Map
->Data
, Copy
.Unwrap(), typed_new_key
);
284 if (Config::FollowRAUW
) {
285 typename
ValueMapT::MapT::iterator I
= Copy
.Map
->Map
.find(Copy
);
286 // I could == Copy.Map->Map.end() if the onRAUW callback already
287 // removed the old mapping.
288 if (I
!= Copy
.Map
->Map
.end()) {
289 ValueT
Target(std::move(I
->second
));
290 Copy
.Map
->Map
.erase(I
); // Definitely destroys *this.
291 Copy
.Map
->insert(std::make_pair(typed_new_key
, std::move(Target
)));
297 template<typename KeyT
, typename ValueT
, typename Config
>
298 struct DenseMapInfo
<ValueMapCallbackVH
<KeyT
, ValueT
, Config
>> {
299 using VH
= ValueMapCallbackVH
<KeyT
, ValueT
, Config
>;
301 static inline VH
getEmptyKey() {
302 return VH(DenseMapInfo
<Value
*>::getEmptyKey());
305 static inline VH
getTombstoneKey() {
306 return VH(DenseMapInfo
<Value
*>::getTombstoneKey());
309 static unsigned getHashValue(const VH
&Val
) {
310 return DenseMapInfo
<KeyT
>::getHashValue(Val
.Unwrap());
313 static unsigned getHashValue(const KeyT
&Val
) {
314 return DenseMapInfo
<KeyT
>::getHashValue(Val
);
317 static bool isEqual(const VH
&LHS
, const VH
&RHS
) {
321 static bool isEqual(const KeyT
&LHS
, const VH
&RHS
) {
322 return LHS
== RHS
.getValPtr();
326 template<typename DenseMapT
, typename KeyT
>
327 class ValueMapIterator
:
328 public std::iterator
<std::forward_iterator_tag
,
329 std::pair
<KeyT
, typename
DenseMapT::mapped_type
>,
331 using BaseT
= typename
DenseMapT::iterator
;
332 using ValueT
= typename
DenseMapT::mapped_type
;
337 ValueMapIterator() : I() {}
338 ValueMapIterator(BaseT I
) : I(I
) {}
340 BaseT
base() const { return I
; }
342 struct ValueTypeProxy
{
346 ValueTypeProxy
*operator->() { return this; }
348 operator std::pair
<KeyT
, ValueT
>() const {
349 return std::make_pair(first
, second
);
353 ValueTypeProxy
operator*() const {
354 ValueTypeProxy Result
= {I
->first
.Unwrap(), I
->second
};
358 ValueTypeProxy
operator->() const {
362 bool operator==(const ValueMapIterator
&RHS
) const {
365 bool operator!=(const ValueMapIterator
&RHS
) const {
369 inline ValueMapIterator
& operator++() { // Preincrement
373 ValueMapIterator
operator++(int) { // Postincrement
374 ValueMapIterator tmp
= *this; ++*this; return tmp
;
378 template<typename DenseMapT
, typename KeyT
>
379 class ValueMapConstIterator
:
380 public std::iterator
<std::forward_iterator_tag
,
381 std::pair
<KeyT
, typename
DenseMapT::mapped_type
>,
383 using BaseT
= typename
DenseMapT::const_iterator
;
384 using ValueT
= typename
DenseMapT::mapped_type
;
389 ValueMapConstIterator() : I() {}
390 ValueMapConstIterator(BaseT I
) : I(I
) {}
391 ValueMapConstIterator(ValueMapIterator
<DenseMapT
, KeyT
> Other
)
394 BaseT
base() const { return I
; }
396 struct ValueTypeProxy
{
398 const ValueT
& second
;
399 ValueTypeProxy
*operator->() { return this; }
400 operator std::pair
<KeyT
, ValueT
>() const {
401 return std::make_pair(first
, second
);
405 ValueTypeProxy
operator*() const {
406 ValueTypeProxy Result
= {I
->first
.Unwrap(), I
->second
};
410 ValueTypeProxy
operator->() const {
414 bool operator==(const ValueMapConstIterator
&RHS
) const {
417 bool operator!=(const ValueMapConstIterator
&RHS
) const {
421 inline ValueMapConstIterator
& operator++() { // Preincrement
425 ValueMapConstIterator
operator++(int) { // Postincrement
426 ValueMapConstIterator tmp
= *this; ++*this; return tmp
;
430 } // end namespace llvm
432 #endif // LLVM_IR_VALUEMAP_H