ValueHandle.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- ValueHandle.h - Value Smart Pointer classes --------------*- 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 declares the ValueHandle class and its sub-classes.
  15. //
  16. //===----------------------------------------------------------------------===//
  17. #ifndef LLVM_IR_VALUEHANDLE_H
  18. #define LLVM_IR_VALUEHANDLE_H
  19. #include "llvm/ADT/DenseMapInfo.h"
  20. #include "llvm/ADT/PointerIntPair.h"
  21. #include "llvm/IR/Value.h"
  22. #include "llvm/Support/Casting.h"
  23. #include <cassert>
  24. namespace llvm {
  25. /// This is the common base class of value handles.
  26. ///
  27. /// ValueHandle's are smart pointers to Value's that have special behavior when
  28. /// the value is deleted or ReplaceAllUsesWith'd. See the specific handles
  29. /// below for details.
  30. class ValueHandleBase {
  31. friend class Value;
  32. protected:
  33. /// This indicates what sub class the handle actually is.
  34. ///
  35. /// This is to avoid having a vtable for the light-weight handle pointers. The
  36. /// fully general Callback version does have a vtable.
  37. enum HandleBaseKind { Assert, Callback, Weak, WeakTracking };
  38. ValueHandleBase(const ValueHandleBase &RHS)
  39. : ValueHandleBase(RHS.PrevPair.getInt(), RHS) {}
  40. ValueHandleBase(HandleBaseKind Kind, const ValueHandleBase &RHS)
  41. : PrevPair(nullptr, Kind), Val(RHS.getValPtr()) {
  42. if (isValid(getValPtr()))
  43. AddToExistingUseList(RHS.getPrevPtr());
  44. }
  45. private:
  46. PointerIntPair<ValueHandleBase**, 2, HandleBaseKind> PrevPair;
  47. ValueHandleBase *Next = nullptr;
  48. Value *Val = nullptr;
  49. void setValPtr(Value *V) { Val = V; }
  50. public:
  51. explicit ValueHandleBase(HandleBaseKind Kind)
  52. : PrevPair(nullptr, Kind) {}
  53. ValueHandleBase(HandleBaseKind Kind, Value *V)
  54. : PrevPair(nullptr, Kind), Val(V) {
  55. if (isValid(getValPtr()))
  56. AddToUseList();
  57. }
  58. ~ValueHandleBase() {
  59. if (isValid(getValPtr()))
  60. RemoveFromUseList();
  61. }
  62. Value *operator=(Value *RHS) {
  63. if (getValPtr() == RHS)
  64. return RHS;
  65. if (isValid(getValPtr()))
  66. RemoveFromUseList();
  67. setValPtr(RHS);
  68. if (isValid(getValPtr()))
  69. AddToUseList();
  70. return RHS;
  71. }
  72. Value *operator=(const ValueHandleBase &RHS) {
  73. if (getValPtr() == RHS.getValPtr())
  74. return RHS.getValPtr();
  75. if (isValid(getValPtr()))
  76. RemoveFromUseList();
  77. setValPtr(RHS.getValPtr());
  78. if (isValid(getValPtr()))
  79. AddToExistingUseList(RHS.getPrevPtr());
  80. return getValPtr();
  81. }
  82. Value *operator->() const { return getValPtr(); }
  83. Value &operator*() const {
  84. Value *V = getValPtr();
  85. assert(V && "Dereferencing deleted ValueHandle");
  86. return *V;
  87. }
  88. protected:
  89. Value *getValPtr() const { return Val; }
  90. static bool isValid(Value *V) {
  91. return V &&
  92. V != DenseMapInfo<Value *>::getEmptyKey() &&
  93. V != DenseMapInfo<Value *>::getTombstoneKey();
  94. }
  95. /// Remove this ValueHandle from its current use list.
  96. void RemoveFromUseList();
  97. /// Clear the underlying pointer without clearing the use list.
  98. ///
  99. /// This should only be used if a derived class has manually removed the
  100. /// handle from the use list.
  101. void clearValPtr() { setValPtr(nullptr); }
  102. public:
  103. // Callbacks made from Value.
  104. static void ValueIsDeleted(Value *V);
  105. static void ValueIsRAUWd(Value *Old, Value *New);
  106. private:
  107. // Internal implementation details.
  108. ValueHandleBase **getPrevPtr() const { return PrevPair.getPointer(); }
  109. HandleBaseKind getKind() const { return PrevPair.getInt(); }
  110. void setPrevPtr(ValueHandleBase **Ptr) { PrevPair.setPointer(Ptr); }
  111. /// Add this ValueHandle to the use list for V.
  112. ///
  113. /// List is the address of either the head of the list or a Next node within
  114. /// the existing use list.
  115. void AddToExistingUseList(ValueHandleBase **List);
  116. /// Add this ValueHandle to the use list after Node.
  117. void AddToExistingUseListAfter(ValueHandleBase *Node);
  118. /// Add this ValueHandle to the use list for V.
  119. void AddToUseList();
  120. };
  121. /// A nullable Value handle that is nullable.
  122. ///
  123. /// This is a value handle that points to a value, and nulls itself
  124. /// out if that value is deleted.
  125. class WeakVH : public ValueHandleBase {
  126. public:
  127. WeakVH() : ValueHandleBase(Weak) {}
  128. WeakVH(Value *P) : ValueHandleBase(Weak, P) {}
  129. WeakVH(const WeakVH &RHS)
  130. : ValueHandleBase(Weak, RHS) {}
  131. WeakVH &operator=(const WeakVH &RHS) = default;
  132. Value *operator=(Value *RHS) {
  133. return ValueHandleBase::operator=(RHS);
  134. }
  135. Value *operator=(const ValueHandleBase &RHS) {
  136. return ValueHandleBase::operator=(RHS);
  137. }
  138. operator Value*() const {
  139. return getValPtr();
  140. }
  141. };
  142. // Specialize simplify_type to allow WeakVH to participate in
  143. // dyn_cast, isa, etc.
  144. template <> struct simplify_type<WeakVH> {
  145. using SimpleType = Value *;
  146. static SimpleType getSimplifiedValue(WeakVH &WVH) { return WVH; }
  147. };
  148. template <> struct simplify_type<const WeakVH> {
  149. using SimpleType = Value *;
  150. static SimpleType getSimplifiedValue(const WeakVH &WVH) { return WVH; }
  151. };
  152. // Specialize DenseMapInfo to allow WeakVH to participate in DenseMap.
  153. template <> struct DenseMapInfo<WeakVH> {
  154. static inline WeakVH getEmptyKey() {
  155. return WeakVH(DenseMapInfo<Value *>::getEmptyKey());
  156. }
  157. static inline WeakVH getTombstoneKey() {
  158. return WeakVH(DenseMapInfo<Value *>::getTombstoneKey());
  159. }
  160. static unsigned getHashValue(const WeakVH &Val) {
  161. return DenseMapInfo<Value *>::getHashValue(Val);
  162. }
  163. static bool isEqual(const WeakVH &LHS, const WeakVH &RHS) {
  164. return DenseMapInfo<Value *>::isEqual(LHS, RHS);
  165. }
  166. };
  167. /// Value handle that is nullable, but tries to track the Value.
  168. ///
  169. /// This is a value handle that tries hard to point to a Value, even across
  170. /// RAUW operations, but will null itself out if the value is destroyed. this
  171. /// is useful for advisory sorts of information, but should not be used as the
  172. /// key of a map (since the map would have to rearrange itself when the pointer
  173. /// changes).
  174. class WeakTrackingVH : public ValueHandleBase {
  175. public:
  176. WeakTrackingVH() : ValueHandleBase(WeakTracking) {}
  177. WeakTrackingVH(Value *P) : ValueHandleBase(WeakTracking, P) {}
  178. WeakTrackingVH(const WeakTrackingVH &RHS)
  179. : ValueHandleBase(WeakTracking, RHS) {}
  180. WeakTrackingVH &operator=(const WeakTrackingVH &RHS) = default;
  181. Value *operator=(Value *RHS) {
  182. return ValueHandleBase::operator=(RHS);
  183. }
  184. Value *operator=(const ValueHandleBase &RHS) {
  185. return ValueHandleBase::operator=(RHS);
  186. }
  187. operator Value*() const {
  188. return getValPtr();
  189. }
  190. bool pointsToAliveValue() const {
  191. return ValueHandleBase::isValid(getValPtr());
  192. }
  193. };
  194. // Specialize simplify_type to allow WeakTrackingVH to participate in
  195. // dyn_cast, isa, etc.
  196. template <> struct simplify_type<WeakTrackingVH> {
  197. using SimpleType = Value *;
  198. static SimpleType getSimplifiedValue(WeakTrackingVH &WVH) { return WVH; }
  199. };
  200. template <> struct simplify_type<const WeakTrackingVH> {
  201. using SimpleType = Value *;
  202. static SimpleType getSimplifiedValue(const WeakTrackingVH &WVH) {
  203. return WVH;
  204. }
  205. };
  206. /// Value handle that asserts if the Value is deleted.
  207. ///
  208. /// This is a Value Handle that points to a value and asserts out if the value
  209. /// is destroyed while the handle is still live. This is very useful for
  210. /// catching dangling pointer bugs and other things which can be non-obvious.
  211. /// One particularly useful place to use this is as the Key of a map. Dangling
  212. /// pointer bugs often lead to really subtle bugs that only occur if another
  213. /// object happens to get allocated to the same address as the old one. Using
  214. /// an AssertingVH ensures that an assert is triggered as soon as the bad
  215. /// delete occurs.
  216. ///
  217. /// Note that an AssertingVH handle does *not* follow values across RAUW
  218. /// operations. This means that RAUW's need to explicitly update the
  219. /// AssertingVH's as it moves. This is required because in non-assert mode this
  220. /// class turns into a trivial wrapper around a pointer.
  221. template <typename ValueTy>
  222. class AssertingVH
  223. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  224. : public ValueHandleBase
  225. #endif
  226. {
  227. friend struct DenseMapInfo<AssertingVH<ValueTy>>;
  228. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  229. Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
  230. void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
  231. #else
  232. Value *ThePtr;
  233. Value *getRawValPtr() const { return ThePtr; }
  234. void setRawValPtr(Value *P) { ThePtr = P; }
  235. #endif
  236. // Convert a ValueTy*, which may be const, to the raw Value*.
  237. static Value *GetAsValue(Value *V) { return V; }
  238. static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
  239. ValueTy *getValPtr() const { return static_cast<ValueTy *>(getRawValPtr()); }
  240. void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
  241. public:
  242. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  243. AssertingVH() : ValueHandleBase(Assert) {}
  244. AssertingVH(ValueTy *P) : ValueHandleBase(Assert, GetAsValue(P)) {}
  245. AssertingVH(const AssertingVH &RHS) : ValueHandleBase(Assert, RHS) {}
  246. #else
  247. AssertingVH() : ThePtr(nullptr) {}
  248. AssertingVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
  249. AssertingVH(const AssertingVH &) = default;
  250. #endif
  251. operator ValueTy*() const {
  252. return getValPtr();
  253. }
  254. ValueTy *operator=(ValueTy *RHS) {
  255. setValPtr(RHS);
  256. return getValPtr();
  257. }
  258. ValueTy *operator=(const AssertingVH<ValueTy> &RHS) {
  259. setValPtr(RHS.getValPtr());
  260. return getValPtr();
  261. }
  262. ValueTy *operator->() const { return getValPtr(); }
  263. ValueTy &operator*() const { return *getValPtr(); }
  264. };
  265. // Treat AssertingVH<T> like T* inside maps. This also allows using find_as()
  266. // to look up a value without constructing a value handle.
  267. template<typename T>
  268. struct DenseMapInfo<AssertingVH<T>> : DenseMapInfo<T *> {};
  269. /// Value handle that tracks a Value across RAUW.
  270. ///
  271. /// TrackingVH is designed for situations where a client needs to hold a handle
  272. /// to a Value (or subclass) across some operations which may move that value,
  273. /// but should never destroy it or replace it with some unacceptable type.
  274. ///
  275. /// It is an error to attempt to replace a value with one of a type which is
  276. /// incompatible with any of its outstanding TrackingVHs.
  277. ///
  278. /// It is an error to read from a TrackingVH that does not point to a valid
  279. /// value. A TrackingVH is said to not point to a valid value if either it
  280. /// hasn't yet been assigned a value yet or because the value it was tracking
  281. /// has since been deleted.
  282. ///
  283. /// Assigning a value to a TrackingVH is always allowed, even if said TrackingVH
  284. /// no longer points to a valid value.
  285. template <typename ValueTy> class TrackingVH {
  286. WeakTrackingVH InnerHandle;
  287. public:
  288. ValueTy *getValPtr() const {
  289. assert(InnerHandle.pointsToAliveValue() &&
  290. "TrackingVH must be non-null and valid on dereference!");
  291. // Check that the value is a member of the correct subclass. We would like
  292. // to check this property on assignment for better debugging, but we don't
  293. // want to require a virtual interface on this VH. Instead we allow RAUW to
  294. // replace this value with a value of an invalid type, and check it here.
  295. assert(isa<ValueTy>(InnerHandle) &&
  296. "Tracked Value was replaced by one with an invalid type!");
  297. return cast<ValueTy>(InnerHandle);
  298. }
  299. void setValPtr(ValueTy *P) {
  300. // Assigning to non-valid TrackingVH's are fine so we just unconditionally
  301. // assign here.
  302. InnerHandle = GetAsValue(P);
  303. }
  304. // Convert a ValueTy*, which may be const, to the type the base
  305. // class expects.
  306. static Value *GetAsValue(Value *V) { return V; }
  307. static Value *GetAsValue(const Value *V) { return const_cast<Value*>(V); }
  308. public:
  309. TrackingVH() = default;
  310. TrackingVH(ValueTy *P) { setValPtr(P); }
  311. operator ValueTy*() const {
  312. return getValPtr();
  313. }
  314. ValueTy *operator=(ValueTy *RHS) {
  315. setValPtr(RHS);
  316. return getValPtr();
  317. }
  318. ValueTy *operator->() const { return getValPtr(); }
  319. ValueTy &operator*() const { return *getValPtr(); }
  320. };
  321. /// Value handle with callbacks on RAUW and destruction.
  322. ///
  323. /// This is a value handle that allows subclasses to define callbacks that run
  324. /// when the underlying Value has RAUW called on it or is destroyed. This
  325. /// class can be used as the key of a map, as long as the user takes it out of
  326. /// the map before calling setValPtr() (since the map has to rearrange itself
  327. /// when the pointer changes). Unlike ValueHandleBase, this class has a vtable.
  328. class CallbackVH : public ValueHandleBase {
  329. virtual void anchor();
  330. protected:
  331. ~CallbackVH() = default;
  332. CallbackVH(const CallbackVH &) = default;
  333. CallbackVH &operator=(const CallbackVH &) = default;
  334. void setValPtr(Value *P) {
  335. ValueHandleBase::operator=(P);
  336. }
  337. public:
  338. CallbackVH() : ValueHandleBase(Callback) {}
  339. CallbackVH(Value *P) : ValueHandleBase(Callback, P) {}
  340. CallbackVH(const Value *P) : CallbackVH(const_cast<Value *>(P)) {}
  341. operator Value*() const {
  342. return getValPtr();
  343. }
  344. /// Callback for Value destruction.
  345. ///
  346. /// Called when this->getValPtr() is destroyed, inside ~Value(), so you
  347. /// may call any non-virtual Value method on getValPtr(), but no subclass
  348. /// methods. If WeakTrackingVH were implemented as a CallbackVH, it would use
  349. /// this
  350. /// method to call setValPtr(NULL). AssertingVH would use this method to
  351. /// cause an assertion failure.
  352. ///
  353. /// All implementations must remove the reference from this object to the
  354. /// Value that's being destroyed.
  355. virtual void deleted() { setValPtr(nullptr); }
  356. /// Callback for Value RAUW.
  357. ///
  358. /// Called when this->getValPtr()->replaceAllUsesWith(new_value) is called,
  359. /// _before_ any of the uses have actually been replaced. If WeakTrackingVH
  360. /// were
  361. /// implemented as a CallbackVH, it would use this method to call
  362. /// setValPtr(new_value). AssertingVH would do nothing in this method.
  363. virtual void allUsesReplacedWith(Value *) {}
  364. };
  365. /// Value handle that poisons itself if the Value is deleted.
  366. ///
  367. /// This is a Value Handle that points to a value and poisons itself if the
  368. /// value is destroyed while the handle is still live. This is very useful for
  369. /// catching dangling pointer bugs where an \c AssertingVH cannot be used
  370. /// because the dangling handle needs to outlive the value without ever being
  371. /// used.
  372. ///
  373. /// One particularly useful place to use this is as the Key of a map. Dangling
  374. /// pointer bugs often lead to really subtle bugs that only occur if another
  375. /// object happens to get allocated to the same address as the old one. Using
  376. /// a PoisoningVH ensures that an assert is triggered if looking up a new value
  377. /// in the map finds a handle from the old value.
  378. ///
  379. /// Note that a PoisoningVH handle does *not* follow values across RAUW
  380. /// operations. This means that RAUW's need to explicitly update the
  381. /// PoisoningVH's as it moves. This is required because in non-assert mode this
  382. /// class turns into a trivial wrapper around a pointer.
  383. template <typename ValueTy>
  384. class PoisoningVH final
  385. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  386. : public CallbackVH
  387. #endif
  388. {
  389. friend struct DenseMapInfo<PoisoningVH<ValueTy>>;
  390. // Convert a ValueTy*, which may be const, to the raw Value*.
  391. static Value *GetAsValue(Value *V) { return V; }
  392. static Value *GetAsValue(const Value *V) { return const_cast<Value *>(V); }
  393. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  394. /// A flag tracking whether this value has been poisoned.
  395. ///
  396. /// On delete and RAUW, we leave the value pointer alone so that as a raw
  397. /// pointer it produces the same value (and we fit into the same key of
  398. /// a hash table, etc), but we poison the handle so that any top-level usage
  399. /// will fail.
  400. bool Poisoned = false;
  401. Value *getRawValPtr() const { return ValueHandleBase::getValPtr(); }
  402. void setRawValPtr(Value *P) { ValueHandleBase::operator=(P); }
  403. /// Handle deletion by poisoning the handle.
  404. void deleted() override {
  405. assert(!Poisoned && "Tried to delete an already poisoned handle!");
  406. Poisoned = true;
  407. RemoveFromUseList();
  408. }
  409. /// Handle RAUW by poisoning the handle.
  410. void allUsesReplacedWith(Value *) override {
  411. assert(!Poisoned && "Tried to RAUW an already poisoned handle!");
  412. Poisoned = true;
  413. RemoveFromUseList();
  414. }
  415. #else // LLVM_ENABLE_ABI_BREAKING_CHECKS
  416. Value *ThePtr = nullptr;
  417. Value *getRawValPtr() const { return ThePtr; }
  418. void setRawValPtr(Value *P) { ThePtr = P; }
  419. #endif
  420. ValueTy *getValPtr() const {
  421. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  422. assert(!Poisoned && "Accessed a poisoned value handle!");
  423. #endif
  424. return static_cast<ValueTy *>(getRawValPtr());
  425. }
  426. void setValPtr(ValueTy *P) { setRawValPtr(GetAsValue(P)); }
  427. public:
  428. PoisoningVH() = default;
  429. #if LLVM_ENABLE_ABI_BREAKING_CHECKS
  430. PoisoningVH(ValueTy *P) : CallbackVH(GetAsValue(P)) {}
  431. PoisoningVH(const PoisoningVH &RHS)
  432. : CallbackVH(RHS), Poisoned(RHS.Poisoned) {}
  433. ~PoisoningVH() {
  434. if (Poisoned)
  435. clearValPtr();
  436. }
  437. PoisoningVH &operator=(const PoisoningVH &RHS) {
  438. if (Poisoned)
  439. clearValPtr();
  440. CallbackVH::operator=(RHS);
  441. Poisoned = RHS.Poisoned;
  442. return *this;
  443. }
  444. #else
  445. PoisoningVH(ValueTy *P) : ThePtr(GetAsValue(P)) {}
  446. #endif
  447. operator ValueTy *() const { return getValPtr(); }
  448. ValueTy *operator->() const { return getValPtr(); }
  449. ValueTy &operator*() const { return *getValPtr(); }
  450. };
  451. // Specialize DenseMapInfo to allow PoisoningVH to participate in DenseMap.
  452. template <typename T> struct DenseMapInfo<PoisoningVH<T>> {
  453. static inline PoisoningVH<T> getEmptyKey() {
  454. PoisoningVH<T> Res;
  455. Res.setRawValPtr(DenseMapInfo<Value *>::getEmptyKey());
  456. return Res;
  457. }
  458. static inline PoisoningVH<T> getTombstoneKey() {
  459. PoisoningVH<T> Res;
  460. Res.setRawValPtr(DenseMapInfo<Value *>::getTombstoneKey());
  461. return Res;
  462. }
  463. static unsigned getHashValue(const PoisoningVH<T> &Val) {
  464. return DenseMapInfo<Value *>::getHashValue(Val.getRawValPtr());
  465. }
  466. static bool isEqual(const PoisoningVH<T> &LHS, const PoisoningVH<T> &RHS) {
  467. return DenseMapInfo<Value *>::isEqual(LHS.getRawValPtr(),
  468. RHS.getRawValPtr());
  469. }
  470. // Allow lookup by T* via find_as(), without constructing a temporary
  471. // value handle.
  472. static unsigned getHashValue(const T *Val) {
  473. return DenseMapInfo<Value *>::getHashValue(Val);
  474. }
  475. static bool isEqual(const T *LHS, const PoisoningVH<T> &RHS) {
  476. return DenseMapInfo<Value *>::isEqual(LHS, RHS.getRawValPtr());
  477. }
  478. };
  479. } // end namespace llvm
  480. #endif // LLVM_IR_VALUEHANDLE_H
  481. #ifdef __GNUC__
  482. #pragma GCC diagnostic pop
  483. #endif