PtrUseVisitor.h 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. #pragma once
  2. #ifdef __GNUC__
  3. #pragma GCC diagnostic push
  4. #pragma GCC diagnostic ignored "-Wunused-parameter"
  5. #endif
  6. //===- PtrUseVisitor.h - InstVisitors over a pointers uses ------*- 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. /// \file
  15. /// This file provides a collection of visitors which walk the (instruction)
  16. /// uses of a pointer. These visitors all provide the same essential behavior
  17. /// as an InstVisitor with similar template-based flexibility and
  18. /// implementation strategies.
  19. ///
  20. /// These can be used, for example, to quickly analyze the uses of an alloca,
  21. /// global variable, or function argument.
  22. ///
  23. /// FIXME: Provide a variant which doesn't track offsets and is cheaper.
  24. //
  25. //===----------------------------------------------------------------------===//
  26. #ifndef LLVM_ANALYSIS_PTRUSEVISITOR_H
  27. #define LLVM_ANALYSIS_PTRUSEVISITOR_H
  28. #include "llvm/ADT/APInt.h"
  29. #include "llvm/ADT/PointerIntPair.h"
  30. #include "llvm/ADT/SmallPtrSet.h"
  31. #include "llvm/ADT/SmallVector.h"
  32. #include "llvm/IR/DerivedTypes.h"
  33. #include "llvm/IR/InstVisitor.h"
  34. #include "llvm/IR/IntrinsicInst.h"
  35. #include <cassert>
  36. #include <type_traits>
  37. namespace llvm {
  38. class DataLayout;
  39. class Use;
  40. namespace detail {
  41. /// Implementation of non-dependent functionality for \c PtrUseVisitor.
  42. ///
  43. /// See \c PtrUseVisitor for the public interface and detailed comments about
  44. /// usage. This class is just a helper base class which is not templated and
  45. /// contains all common code to be shared between different instantiations of
  46. /// PtrUseVisitor.
  47. class PtrUseVisitorBase {
  48. public:
  49. /// This class provides information about the result of a visit.
  50. ///
  51. /// After walking all the users (recursively) of a pointer, the basic
  52. /// infrastructure records some commonly useful information such as escape
  53. /// analysis and whether the visit completed or aborted early.
  54. class PtrInfo {
  55. public:
  56. PtrInfo() : AbortedInfo(nullptr, false), EscapedInfo(nullptr, false) {}
  57. /// Reset the pointer info, clearing all state.
  58. void reset() {
  59. AbortedInfo.setPointer(nullptr);
  60. AbortedInfo.setInt(false);
  61. EscapedInfo.setPointer(nullptr);
  62. EscapedInfo.setInt(false);
  63. }
  64. /// Did we abort the visit early?
  65. bool isAborted() const { return AbortedInfo.getInt(); }
  66. /// Is the pointer escaped at some point?
  67. bool isEscaped() const { return EscapedInfo.getInt(); }
  68. /// Get the instruction causing the visit to abort.
  69. /// \returns a pointer to the instruction causing the abort if one is
  70. /// available; otherwise returns null.
  71. Instruction *getAbortingInst() const { return AbortedInfo.getPointer(); }
  72. /// Get the instruction causing the pointer to escape.
  73. /// \returns a pointer to the instruction which escapes the pointer if one
  74. /// is available; otherwise returns null.
  75. Instruction *getEscapingInst() const { return EscapedInfo.getPointer(); }
  76. /// Mark the visit as aborted. Intended for use in a void return.
  77. /// \param I The instruction which caused the visit to abort, if available.
  78. void setAborted(Instruction *I = nullptr) {
  79. AbortedInfo.setInt(true);
  80. AbortedInfo.setPointer(I);
  81. }
  82. /// Mark the pointer as escaped. Intended for use in a void return.
  83. /// \param I The instruction which escapes the pointer, if available.
  84. void setEscaped(Instruction *I = nullptr) {
  85. EscapedInfo.setInt(true);
  86. EscapedInfo.setPointer(I);
  87. }
  88. /// Mark the pointer as escaped, and the visit as aborted. Intended
  89. /// for use in a void return.
  90. /// \param I The instruction which both escapes the pointer and aborts the
  91. /// visit, if available.
  92. void setEscapedAndAborted(Instruction *I = nullptr) {
  93. setEscaped(I);
  94. setAborted(I);
  95. }
  96. private:
  97. PointerIntPair<Instruction *, 1, bool> AbortedInfo, EscapedInfo;
  98. };
  99. protected:
  100. const DataLayout &DL;
  101. /// \name Visitation infrastructure
  102. /// @{
  103. /// The info collected about the pointer being visited thus far.
  104. PtrInfo PI;
  105. /// A struct of the data needed to visit a particular use.
  106. ///
  107. /// This is used to maintain a worklist fo to-visit uses. This is used to
  108. /// make the visit be iterative rather than recursive.
  109. struct UseToVisit {
  110. using UseAndIsOffsetKnownPair = PointerIntPair<Use *, 1, bool>;
  111. UseAndIsOffsetKnownPair UseAndIsOffsetKnown;
  112. APInt Offset;
  113. };
  114. /// The worklist of to-visit uses.
  115. SmallVector<UseToVisit, 8> Worklist;
  116. /// A set of visited uses to break cycles in unreachable code.
  117. SmallPtrSet<Use *, 8> VisitedUses;
  118. /// @}
  119. /// \name Per-visit state
  120. /// This state is reset for each instruction visited.
  121. /// @{
  122. /// The use currently being visited.
  123. Use *U;
  124. /// True if we have a known constant offset for the use currently
  125. /// being visited.
  126. bool IsOffsetKnown;
  127. /// The constant offset of the use if that is known.
  128. APInt Offset;
  129. /// @}
  130. /// Note that the constructor is protected because this class must be a base
  131. /// class, we can't create instances directly of this class.
  132. PtrUseVisitorBase(const DataLayout &DL) : DL(DL) {}
  133. /// Enqueue the users of this instruction in the visit worklist.
  134. ///
  135. /// This will visit the users with the same offset of the current visit
  136. /// (including an unknown offset if that is the current state).
  137. void enqueueUsers(Instruction &I);
  138. /// Walk the operands of a GEP and adjust the offset as appropriate.
  139. ///
  140. /// This routine does the heavy lifting of the pointer walk by computing
  141. /// offsets and looking through GEPs.
  142. bool adjustOffsetForGEP(GetElementPtrInst &GEPI);
  143. };
  144. } // end namespace detail
  145. /// A base class for visitors over the uses of a pointer value.
  146. ///
  147. /// Once constructed, a user can call \c visit on a pointer value, and this
  148. /// will walk its uses and visit each instruction using an InstVisitor. It also
  149. /// provides visit methods which will recurse through any pointer-to-pointer
  150. /// transformations such as GEPs and bitcasts.
  151. ///
  152. /// During the visit, the current Use* being visited is available to the
  153. /// subclass, as well as the current offset from the original base pointer if
  154. /// known.
  155. ///
  156. /// The recursive visit of uses is accomplished with a worklist, so the only
  157. /// ordering guarantee is that an instruction is visited before any uses of it
  158. /// are visited. Note that this does *not* mean before any of its users are
  159. /// visited! This is because users can be visited multiple times due to
  160. /// multiple, different uses of pointers derived from the same base.
  161. ///
  162. /// A particular Use will only be visited once, but a User may be visited
  163. /// multiple times, once per Use. This visits may notably have different
  164. /// offsets.
  165. ///
  166. /// All visit methods on the underlying InstVisitor return a boolean. This
  167. /// return short-circuits the visit, stopping it immediately.
  168. ///
  169. /// FIXME: Generalize this for all values rather than just instructions.
  170. template <typename DerivedT>
  171. class PtrUseVisitor : protected InstVisitor<DerivedT>,
  172. public detail::PtrUseVisitorBase {
  173. friend class InstVisitor<DerivedT>;
  174. using Base = InstVisitor<DerivedT>;
  175. public:
  176. PtrUseVisitor(const DataLayout &DL) : PtrUseVisitorBase(DL) {
  177. static_assert(std::is_base_of<PtrUseVisitor, DerivedT>::value,
  178. "Must pass the derived type to this template!");
  179. }
  180. /// Recursively visit the uses of the given pointer.
  181. /// \returns An info struct about the pointer. See \c PtrInfo for details.
  182. PtrInfo visitPtr(Instruction &I) {
  183. // This must be a pointer type. Get an integer type suitable to hold
  184. // offsets on this pointer.
  185. // FIXME: Support a vector of pointers.
  186. assert(I.getType()->isPointerTy());
  187. IntegerType *IntIdxTy = cast<IntegerType>(DL.getIndexType(I.getType()));
  188. IsOffsetKnown = true;
  189. Offset = APInt(IntIdxTy->getBitWidth(), 0);
  190. PI.reset();
  191. // Enqueue the uses of this pointer.
  192. enqueueUsers(I);
  193. // Visit all the uses off the worklist until it is empty.
  194. while (!Worklist.empty()) {
  195. UseToVisit ToVisit = Worklist.pop_back_val();
  196. U = ToVisit.UseAndIsOffsetKnown.getPointer();
  197. IsOffsetKnown = ToVisit.UseAndIsOffsetKnown.getInt();
  198. if (IsOffsetKnown)
  199. Offset = std::move(ToVisit.Offset);
  200. Instruction *I = cast<Instruction>(U->getUser());
  201. static_cast<DerivedT*>(this)->visit(I);
  202. if (PI.isAborted())
  203. break;
  204. }
  205. return PI;
  206. }
  207. protected:
  208. void visitStoreInst(StoreInst &SI) {
  209. if (SI.getValueOperand() == U->get())
  210. PI.setEscaped(&SI);
  211. }
  212. void visitBitCastInst(BitCastInst &BC) {
  213. enqueueUsers(BC);
  214. }
  215. void visitAddrSpaceCastInst(AddrSpaceCastInst &ASC) {
  216. enqueueUsers(ASC);
  217. }
  218. void visitPtrToIntInst(PtrToIntInst &I) {
  219. PI.setEscaped(&I);
  220. }
  221. void visitGetElementPtrInst(GetElementPtrInst &GEPI) {
  222. if (GEPI.use_empty())
  223. return;
  224. // If we can't walk the GEP, clear the offset.
  225. if (!adjustOffsetForGEP(GEPI)) {
  226. IsOffsetKnown = false;
  227. Offset = APInt();
  228. }
  229. // Enqueue the users now that the offset has been adjusted.
  230. enqueueUsers(GEPI);
  231. }
  232. // No-op intrinsics which we know don't escape the pointer to logic in
  233. // some other function.
  234. void visitDbgInfoIntrinsic(DbgInfoIntrinsic &I) {}
  235. void visitMemIntrinsic(MemIntrinsic &I) {}
  236. void visitIntrinsicInst(IntrinsicInst &II) {
  237. switch (II.getIntrinsicID()) {
  238. default:
  239. return Base::visitIntrinsicInst(II);
  240. case Intrinsic::lifetime_start:
  241. case Intrinsic::lifetime_end:
  242. return; // No-op intrinsics.
  243. }
  244. }
  245. // Generically, arguments to calls and invokes escape the pointer to some
  246. // other function. Mark that.
  247. void visitCallBase(CallBase &CB) {
  248. PI.setEscaped(&CB);
  249. Base::visitCallBase(CB);
  250. }
  251. };
  252. } // end namespace llvm
  253. #endif // LLVM_ANALYSIS_PTRUSEVISITOR_H
  254. #ifdef __GNUC__
  255. #pragma GCC diagnostic pop
  256. #endif