ValueMap.h 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ValueMap.h - Safe map from Values to data ----------------*- C++ -*-===//
  7. //
  8. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  9. // See https://llvm.org/LICENSE.txt for license information.
  10. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  11. //
  12. //===----------------------------------------------------------------------===//
  13. //
  14. // This file defines the ValueMap class. ValueMap maps Value* or any subclass
  15. // to an arbitrary other type. It provides the DenseMap interface but updates
  16. // itself to remain safe when keys are RAUWed or deleted. By default, when a
  17. // key is RAUWed from V1 to V2, the old mapping V1->target is removed, and a new
  18. // mapping V2->target is added. If V2 already existed, its old target is
  19. // overwritten. When a key is deleted, its mapping is removed.
  20. //
  21. // You can override a ValueMap's Config parameter to control exactly what
  22. // happens on RAUW and destruction and to get called back on each event. It's
  23. // legal to call back into the ValueMap from a Config's callbacks. Config
  24. // parameters should inherit from ValueMapConfig<KeyT> to get default
  25. // implementations of all the methods ValueMap uses. See ValueMapConfig for
  26. // documentation of the functions you can override.
  27. //
  28. //===----------------------------------------------------------------------===//
  29. #ifndef LLVM_IR_VALUEMAP_H
  30. #define LLVM_IR_VALUEMAP_H
  31. #include "llvm/ADT/DenseMap.h"
  32. #include "llvm/ADT/DenseMapInfo.h"
  33. #include "llvm/ADT/None.h"
  34. #include "llvm/ADT/Optional.h"
  35. #include "llvm/IR/TrackingMDRef.h"
  36. #include "llvm/IR/ValueHandle.h"
  37. #include "llvm/Support/Casting.h"
  38. #include "llvm/Support/Mutex.h"
  39. #include <algorithm>
  40. #include <cassert>
  41. #include <cstddef>
  42. #include <iterator>
  43. #include <mutex>
  44. #include <type_traits>
  45. #include <utility>
  46. namespace llvm {
  47. template<typename KeyT, typename ValueT, typename Config>
  48. class ValueMapCallbackVH;
  49. template<typename DenseMapT, typename KeyT>
  50. class ValueMapIterator;
  51. template<typename DenseMapT, typename KeyT>
  52. 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;
  59. /// If FollowRAUW is true, the ValueMap will update mappings on RAUW. If it's
  60. /// false, the ValueMap will leave the original mapping in place.
  61. enum { FollowRAUW = true };
  62. // All methods will be called with a first argument of type ExtraData. The
  63. // default implementations in this class take a templated first argument so
  64. // that users' subclasses can use any type they want without having to
  65. // override all the defaults.
  66. struct ExtraData {};
  67. template<typename ExtraDataT>
  68. static void onRAUW(const ExtraDataT & /*Data*/, KeyT /*Old*/, KeyT /*New*/) {}
  69. template<typename ExtraDataT>
  70. static void onDelete(const ExtraDataT &/*Data*/, KeyT /*Old*/) {}
  71. /// Returns a mutex that should be acquired around any changes to the map.
  72. /// This is only acquired from the CallbackVH (and held around calls to onRAUW
  73. /// and onDelete) and not inside other ValueMap methods. NULL means that no
  74. /// mutex is necessary.
  75. template<typename ExtraDataT>
  76. static mutex_type *getMutex(const ExtraDataT &/*Data*/) { return nullptr; }
  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. using ValueMapCVH = ValueMapCallbackVH<KeyT, ValueT, Config>;
  83. using MapT = DenseMap<ValueMapCVH, ValueT, DenseMapInfo<ValueMapCVH>>;
  84. using MDMapT = DenseMap<const Metadata *, TrackingMDRef>;
  85. using ExtraData = typename Config::ExtraData;
  86. MapT Map;
  87. Optional<MDMapT> MDMap;
  88. ExtraData Data;
  89. public:
  90. using key_type = KeyT;
  91. using mapped_type = ValueT;
  92. using value_type = std::pair<KeyT, ValueT>;
  93. using size_type = unsigned;
  94. explicit ValueMap(unsigned NumInitBuckets = 64)
  95. : Map(NumInitBuckets), Data() {}
  96. explicit ValueMap(const ExtraData &Data, unsigned NumInitBuckets = 64)
  97. : Map(NumInitBuckets), Data(Data) {}
  98. // ValueMap can't be copied nor moved, beucase the callbacks store pointer
  99. // to it.
  100. ValueMap(const ValueMap &) = delete;
  101. ValueMap(ValueMap &&) = delete;
  102. ValueMap &operator=(const ValueMap &) = delete;
  103. ValueMap &operator=(ValueMap &&) = delete;
  104. bool hasMD() const { return bool(MDMap); }
  105. MDMapT &MD() {
  106. if (!MDMap)
  107. MDMap.emplace();
  108. return *MDMap;
  109. }
  110. Optional<MDMapT> &getMDMap() { return MDMap; }
  111. /// Get the mapped metadata, if it's in the map.
  112. Optional<Metadata *> getMappedMD(const Metadata *MD) const {
  113. if (!MDMap)
  114. return None;
  115. auto Where = MDMap->find(MD);
  116. if (Where == MDMap->end())
  117. return None;
  118. return Where->second.get();
  119. }
  120. using iterator = ValueMapIterator<MapT, KeyT>;
  121. using const_iterator = ValueMapConstIterator<MapT, KeyT>;
  122. inline iterator begin() { return iterator(Map.begin()); }
  123. inline iterator end() { return iterator(Map.end()); }
  124. inline const_iterator begin() const { return const_iterator(Map.begin()); }
  125. inline const_iterator end() const { return const_iterator(Map.end()); }
  126. bool empty() const { return Map.empty(); }
  127. size_type size() const { return Map.size(); }
  128. /// Grow the map so that it has at least Size buckets. Does not shrink
  129. void resize(size_t Size) { Map.resize(Size); }
  130. void clear() {
  131. Map.clear();
  132. MDMap.reset();
  133. }
  134. /// Return 1 if the specified key is in the map, 0 otherwise.
  135. size_type count(const KeyT &Val) const {
  136. return Map.find_as(Val) == Map.end() ? 0 : 1;
  137. }
  138. iterator find(const KeyT &Val) {
  139. return iterator(Map.find_as(Val));
  140. }
  141. const_iterator find(const KeyT &Val) const {
  142. return const_iterator(Map.find_as(Val));
  143. }
  144. /// lookup - Return the entry for the specified key, or a default
  145. /// constructed value if no such entry exists.
  146. ValueT lookup(const KeyT &Val) const {
  147. typename MapT::const_iterator I = Map.find_as(Val);
  148. return I != Map.end() ? I->second : ValueT();
  149. }
  150. // Inserts key,value pair into the map if the key isn't already in the map.
  151. // If the key is already in the map, it returns false and doesn't update the
  152. // value.
  153. std::pair<iterator, bool> insert(const std::pair<KeyT, ValueT> &KV) {
  154. auto MapResult = Map.insert(std::make_pair(Wrap(KV.first), KV.second));
  155. return std::make_pair(iterator(MapResult.first), MapResult.second);
  156. }
  157. std::pair<iterator, bool> insert(std::pair<KeyT, ValueT> &&KV) {
  158. auto MapResult =
  159. Map.insert(std::make_pair(Wrap(KV.first), std::move(KV.second)));
  160. return std::make_pair(iterator(MapResult.first), MapResult.second);
  161. }
  162. /// insert - Range insertion of pairs.
  163. template<typename InputIt>
  164. void insert(InputIt I, InputIt E) {
  165. for (; I != E; ++I)
  166. insert(*I);
  167. }
  168. bool erase(const KeyT &Val) {
  169. typename MapT::iterator I = Map.find_as(Val);
  170. if (I == Map.end())
  171. return false;
  172. Map.erase(I);
  173. return true;
  174. }
  175. void erase(iterator I) {
  176. return Map.erase(I.base());
  177. }
  178. value_type& FindAndConstruct(const KeyT &Key) {
  179. return Map.FindAndConstruct(Wrap(Key));
  180. }
  181. ValueT &operator[](const KeyT &Key) {
  182. return Map[Wrap(Key)];
  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. /// getPointerIntoBucketsArray() - Return an opaque pointer into the buckets
  191. /// array. In conjunction with the previous method, this can be used to
  192. /// determine whether an insertion caused the ValueMap to reallocate.
  193. const void *getPointerIntoBucketsArray() const {
  194. return Map.getPointerIntoBucketsArray();
  195. }
  196. private:
  197. // Takes a key being looked up in the map and wraps it into a
  198. // ValueMapCallbackVH, the actual key type of the map. We use a helper
  199. // function because ValueMapCVH is constructed with a second parameter.
  200. ValueMapCVH Wrap(KeyT key) const {
  201. // The only way the resulting CallbackVH could try to modify *this (making
  202. // the const_cast incorrect) is if it gets inserted into the map. But then
  203. // this function must have been called from a non-const method, making the
  204. // const_cast ok.
  205. return ValueMapCVH(key, const_cast<ValueMap*>(this));
  206. }
  207. };
  208. // This CallbackVH updates its ValueMap when the contained Value changes,
  209. // according to the user's preferences expressed through the Config object.
  210. template <typename KeyT, typename ValueT, typename Config>
  211. class ValueMapCallbackVH final : public CallbackVH {
  212. friend class ValueMap<KeyT, ValueT, Config>;
  213. friend struct DenseMapInfo<ValueMapCallbackVH>;
  214. using ValueMapT = ValueMap<KeyT, ValueT, Config>;
  215. using KeySansPointerT = std::remove_pointer_t<KeyT>;
  216. ValueMapT *Map;
  217. ValueMapCallbackVH(KeyT Key, ValueMapT *Map)
  218. : CallbackVH(const_cast<Value*>(static_cast<const Value*>(Key))),
  219. Map(Map) {}
  220. // Private constructor used to create empty/tombstone DenseMap keys.
  221. ValueMapCallbackVH(Value *V) : CallbackVH(V), Map(nullptr) {}
  222. public:
  223. KeyT Unwrap() const { return cast_or_null<KeySansPointerT>(getValPtr()); }
  224. void deleted() override {
  225. // Make a copy that won't get changed even when *this is destroyed.
  226. ValueMapCallbackVH Copy(*this);
  227. typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
  228. std::unique_lock<typename Config::mutex_type> Guard;
  229. if (M)
  230. Guard = std::unique_lock<typename Config::mutex_type>(*M);
  231. Config::onDelete(Copy.Map->Data, Copy.Unwrap()); // May destroy *this.
  232. Copy.Map->Map.erase(Copy); // Definitely destroys *this.
  233. }
  234. void allUsesReplacedWith(Value *new_key) override {
  235. assert(isa<KeySansPointerT>(new_key) &&
  236. "Invalid RAUW on key of ValueMap<>");
  237. // Make a copy that won't get changed even when *this is destroyed.
  238. ValueMapCallbackVH Copy(*this);
  239. typename Config::mutex_type *M = Config::getMutex(Copy.Map->Data);
  240. std::unique_lock<typename Config::mutex_type> Guard;
  241. if (M)
  242. Guard = std::unique_lock<typename Config::mutex_type>(*M);
  243. KeyT typed_new_key = cast<KeySansPointerT>(new_key);
  244. // Can destroy *this:
  245. Config::onRAUW(Copy.Map->Data, Copy.Unwrap(), typed_new_key);
  246. if (Config::FollowRAUW) {
  247. typename ValueMapT::MapT::iterator I = Copy.Map->Map.find(Copy);
  248. // I could == Copy.Map->Map.end() if the onRAUW callback already
  249. // removed the old mapping.
  250. if (I != Copy.Map->Map.end()) {
  251. ValueT Target(std::move(I->second));
  252. Copy.Map->Map.erase(I); // Definitely destroys *this.
  253. Copy.Map->insert(std::make_pair(typed_new_key, std::move(Target)));
  254. }
  255. }
  256. }
  257. };
  258. template<typename KeyT, typename ValueT, typename Config>
  259. struct DenseMapInfo<ValueMapCallbackVH<KeyT, ValueT, Config>> {
  260. using VH = ValueMapCallbackVH<KeyT, ValueT, Config>;
  261. static inline VH getEmptyKey() {
  262. return VH(DenseMapInfo<Value *>::getEmptyKey());
  263. }
  264. static inline VH getTombstoneKey() {
  265. return VH(DenseMapInfo<Value *>::getTombstoneKey());
  266. }
  267. static unsigned getHashValue(const VH &Val) {
  268. return DenseMapInfo<KeyT>::getHashValue(Val.Unwrap());
  269. }
  270. static unsigned getHashValue(const KeyT &Val) {
  271. return DenseMapInfo<KeyT>::getHashValue(Val);
  272. }
  273. static bool isEqual(const VH &LHS, const VH &RHS) {
  274. return LHS == RHS;
  275. }
  276. static bool isEqual(const KeyT &LHS, const VH &RHS) {
  277. return LHS == RHS.getValPtr();
  278. }
  279. };
  280. template <typename DenseMapT, typename KeyT> class ValueMapIterator {
  281. using BaseT = typename DenseMapT::iterator;
  282. using ValueT = typename DenseMapT::mapped_type;
  283. BaseT I;
  284. public:
  285. using iterator_category = std::forward_iterator_tag;
  286. using value_type = std::pair<KeyT, typename DenseMapT::mapped_type>;
  287. using difference_type = std::ptrdiff_t;
  288. using pointer = value_type *;
  289. using reference = value_type &;
  290. ValueMapIterator() : I() {}
  291. ValueMapIterator(BaseT I) : I(I) {}
  292. BaseT base() const { return I; }
  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. ValueTypeProxy operator*() const {
  302. ValueTypeProxy Result = {I->first.Unwrap(), I->second};
  303. return Result;
  304. }
  305. ValueTypeProxy operator->() const {
  306. return operator*();
  307. }
  308. bool operator==(const ValueMapIterator &RHS) const {
  309. return I == RHS.I;
  310. }
  311. bool operator!=(const ValueMapIterator &RHS) const {
  312. return I != RHS.I;
  313. }
  314. inline ValueMapIterator& operator++() { // Preincrement
  315. ++I;
  316. return *this;
  317. }
  318. ValueMapIterator operator++(int) { // Postincrement
  319. ValueMapIterator tmp = *this; ++*this; return tmp;
  320. }
  321. };
  322. template <typename DenseMapT, typename KeyT> class ValueMapConstIterator {
  323. using BaseT = typename DenseMapT::const_iterator;
  324. using ValueT = typename DenseMapT::mapped_type;
  325. BaseT I;
  326. public:
  327. using iterator_category = std::forward_iterator_tag;
  328. using value_type = std::pair<KeyT, typename DenseMapT::mapped_type>;
  329. using difference_type = std::ptrdiff_t;
  330. using pointer = value_type *;
  331. using reference = value_type &;
  332. ValueMapConstIterator() : I() {}
  333. ValueMapConstIterator(BaseT I) : I(I) {}
  334. ValueMapConstIterator(ValueMapIterator<DenseMapT, KeyT> Other)
  335. : I(Other.base()) {}
  336. BaseT base() const { return I; }
  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. ValueTypeProxy operator*() const {
  346. ValueTypeProxy Result = {I->first.Unwrap(), I->second};
  347. return Result;
  348. }
  349. ValueTypeProxy operator->() const {
  350. return operator*();
  351. }
  352. bool operator==(const ValueMapConstIterator &RHS) const {
  353. return I == RHS.I;
  354. }
  355. bool operator!=(const ValueMapConstIterator &RHS) const {
  356. return I != RHS.I;
  357. }
  358. inline ValueMapConstIterator& operator++() { // Preincrement
  359. ++I;
  360. return *this;
  361. }
  362. ValueMapConstIterator operator++(int) { // Postincrement
  363. ValueMapConstIterator tmp = *this; ++*this; return tmp;
  364. }
  365. };
  366. } // end namespace llvm
  367. #endif // LLVM_IR_VALUEMAP_H
  368. #ifdef __GNUC__
  369. #pragma GCC diagnostic pop
  370. #endif