CaptureTracking.cpp 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  1. //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
  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 contains routines that help determine which pointers are captured.
  11. // A pointer value is captured if the function makes a copy of any part of the
  12. // pointer that outlives the call. Not being captured means, more or less, that
  13. // the pointer is only dereferenced and not stored in a global. Returning part
  14. // of the pointer as the function return value may or may not count as capturing
  15. // the pointer, depending on the context.
  16. //
  17. //===----------------------------------------------------------------------===//
  18. #include "llvm/ADT/SmallSet.h"
  19. #include "llvm/ADT/SmallVector.h"
  20. #include "llvm/Analysis/AliasAnalysis.h"
  21. #include "llvm/Analysis/CFG.h"
  22. #include "llvm/Analysis/CaptureTracking.h"
  23. #include "llvm/IR/CallSite.h"
  24. #include "llvm/IR/Constants.h"
  25. #include "llvm/IR/Dominators.h"
  26. #include "llvm/IR/Instructions.h"
  27. using namespace llvm;
  28. CaptureTracker::~CaptureTracker() {}
  29. bool CaptureTracker::shouldExplore(const Use *U) { return true; }
  30. namespace {
  31. struct SimpleCaptureTracker : public CaptureTracker {
  32. explicit SimpleCaptureTracker(bool ReturnCaptures)
  33. : ReturnCaptures(ReturnCaptures), Captured(false) {}
  34. void tooManyUses() override { Captured = true; }
  35. bool captured(const Use *U) override {
  36. if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
  37. return false;
  38. Captured = true;
  39. return true;
  40. }
  41. bool ReturnCaptures;
  42. bool Captured;
  43. };
  44. struct NumberedInstCache {
  45. SmallDenseMap<const Instruction *, unsigned, 32> NumberedInsts;
  46. BasicBlock::const_iterator LastInstFound;
  47. unsigned LastInstPos;
  48. const BasicBlock *BB;
  49. NumberedInstCache(const BasicBlock *BasicB) : LastInstPos(0), BB(BasicB) {
  50. LastInstFound = BB->end();
  51. }
  52. /// \brief Find the first instruction 'A' or 'B' in 'BB'. Number out
  53. /// instruction while walking 'BB'.
  54. const Instruction *find(const Instruction *A, const Instruction *B) {
  55. const Instruction *Inst = nullptr;
  56. assert(!(LastInstFound == BB->end() && LastInstPos != 0) &&
  57. "Instruction supposed to be in NumberedInsts");
  58. // Start the search with the instruction found in the last lookup round.
  59. auto II = BB->begin();
  60. auto IE = BB->end();
  61. if (LastInstFound != IE)
  62. II = std::next(LastInstFound);
  63. // Number all instructions up to the point where we find 'A' or 'B'.
  64. for (++LastInstPos; II != IE; ++II, ++LastInstPos) {
  65. Inst = cast<Instruction>(II);
  66. NumberedInsts[Inst] = LastInstPos;
  67. if (Inst == A || Inst == B)
  68. break;
  69. }
  70. assert(II != IE && "Instruction not found?");
  71. LastInstFound = II;
  72. return Inst;
  73. }
  74. /// \brief Find out whether 'A' dominates 'B', meaning whether 'A'
  75. /// comes before 'B' in 'BB'. This is a simplification that considers
  76. /// cached instruction positions and ignores other basic blocks, being
  77. /// only relevant to compare relative instructions positions inside 'BB'.
  78. bool dominates(const Instruction *A, const Instruction *B) {
  79. assert(A->getParent() == B->getParent() &&
  80. "Instructions must be in the same basic block!");
  81. unsigned NA = NumberedInsts.lookup(A);
  82. unsigned NB = NumberedInsts.lookup(B);
  83. if (NA && NB)
  84. return NA < NB;
  85. if (NA)
  86. return true;
  87. if (NB)
  88. return false;
  89. return A == find(A, B);
  90. }
  91. };
  92. /// Only find pointer captures which happen before the given instruction. Uses
  93. /// the dominator tree to determine whether one instruction is before another.
  94. /// Only support the case where the Value is defined in the same basic block
  95. /// as the given instruction and the use.
  96. struct CapturesBefore : public CaptureTracker {
  97. CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT,
  98. bool IncludeI)
  99. : LocalInstCache(I->getParent()), BeforeHere(I), DT(DT),
  100. ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {}
  101. void tooManyUses() override { Captured = true; }
  102. bool isSafeToPrune(Instruction *I) {
  103. BasicBlock *BB = I->getParent();
  104. // We explore this usage only if the usage can reach "BeforeHere".
  105. // If use is not reachable from entry, there is no need to explore.
  106. if (BeforeHere != I && !DT->isReachableFromEntry(BB))
  107. return true;
  108. // Compute the case where both instructions are inside the same basic
  109. // block. Since instructions in the same BB as BeforeHere are numbered in
  110. // 'LocalInstCache', avoid using 'dominates' and 'isPotentiallyReachable'
  111. // which are very expensive for large basic blocks.
  112. if (BB == BeforeHere->getParent()) {
  113. // 'I' dominates 'BeforeHere' => not safe to prune.
  114. //
  115. // The value defined by an invoke dominates an instruction only if it
  116. // dominates every instruction in UseBB. A PHI is dominated only if
  117. // the instruction dominates every possible use in the UseBB. Since
  118. // UseBB == BB, avoid pruning.
  119. if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I) || I == BeforeHere)
  120. return false;
  121. if (!LocalInstCache.dominates(BeforeHere, I))
  122. return false;
  123. // 'BeforeHere' comes before 'I', it's safe to prune if we also
  124. // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or
  125. // by its successors, i.e, prune if:
  126. //
  127. // (1) BB is an entry block or have no sucessors.
  128. // (2) There's no path coming back through BB sucessors.
  129. if (BB == &BB->getParent()->getEntryBlock() ||
  130. !BB->getTerminator()->getNumSuccessors())
  131. return true;
  132. SmallVector<BasicBlock*, 32> Worklist;
  133. Worklist.append(succ_begin(BB), succ_end(BB));
  134. if (!isPotentiallyReachableFromMany(Worklist, BB, DT))
  135. return true;
  136. return false;
  137. }
  138. // If the value is defined in the same basic block as use and BeforeHere,
  139. // there is no need to explore the use if BeforeHere dominates use.
  140. // Check whether there is a path from I to BeforeHere.
  141. if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
  142. !isPotentiallyReachable(I, BeforeHere, DT))
  143. return true;
  144. return false;
  145. }
  146. bool shouldExplore(const Use *U) override {
  147. Instruction *I = cast<Instruction>(U->getUser());
  148. if (BeforeHere == I && !IncludeI)
  149. return false;
  150. if (isSafeToPrune(I))
  151. return false;
  152. return true;
  153. }
  154. bool captured(const Use *U) override {
  155. if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
  156. return false;
  157. if (!shouldExplore(U))
  158. return false;
  159. Captured = true;
  160. return true;
  161. }
  162. NumberedInstCache LocalInstCache;
  163. const Instruction *BeforeHere;
  164. DominatorTree *DT;
  165. bool ReturnCaptures;
  166. bool IncludeI;
  167. bool Captured;
  168. };
  169. }
  170. /// PointerMayBeCaptured - Return true if this pointer value may be captured
  171. /// by the enclosing function (which is required to exist). This routine can
  172. /// be expensive, so consider caching the results. The boolean ReturnCaptures
  173. /// specifies whether returning the value (or part of it) from the function
  174. /// counts as capturing it or not. The boolean StoreCaptures specified whether
  175. /// storing the value (or part of it) into memory anywhere automatically
  176. /// counts as capturing it or not.
  177. bool llvm::PointerMayBeCaptured(const Value *V,
  178. bool ReturnCaptures, bool StoreCaptures) {
  179. assert(!isa<GlobalValue>(V) &&
  180. "It doesn't make sense to ask whether a global is captured.");
  181. // TODO: If StoreCaptures is not true, we could do Fancy analysis
  182. // to determine whether this store is not actually an escape point.
  183. // In that case, BasicAliasAnalysis should be updated as well to
  184. // take advantage of this.
  185. (void)StoreCaptures;
  186. SimpleCaptureTracker SCT(ReturnCaptures);
  187. PointerMayBeCaptured(V, &SCT);
  188. return SCT.Captured;
  189. }
  190. /// PointerMayBeCapturedBefore - Return true if this pointer value may be
  191. /// captured by the enclosing function (which is required to exist). If a
  192. /// DominatorTree is provided, only captures which happen before the given
  193. /// instruction are considered. This routine can be expensive, so consider
  194. /// caching the results. The boolean ReturnCaptures specifies whether
  195. /// returning the value (or part of it) from the function counts as capturing
  196. /// it or not. The boolean StoreCaptures specified whether storing the value
  197. /// (or part of it) into memory anywhere automatically counts as capturing it
  198. /// or not.
  199. bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
  200. bool StoreCaptures, const Instruction *I,
  201. DominatorTree *DT, bool IncludeI) {
  202. assert(!isa<GlobalValue>(V) &&
  203. "It doesn't make sense to ask whether a global is captured.");
  204. if (!DT)
  205. return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
  206. // TODO: See comment in PointerMayBeCaptured regarding what could be done
  207. // with StoreCaptures.
  208. CapturesBefore CB(ReturnCaptures, I, DT, IncludeI);
  209. PointerMayBeCaptured(V, &CB);
  210. return CB.Captured;
  211. }
  212. /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
  213. /// a cache. Then we can move the code from BasicAliasAnalysis into
  214. /// that path, and remove this threshold.
  215. static int const Threshold = 20;
  216. void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
  217. assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
  218. SmallVector<const Use *, Threshold> Worklist;
  219. SmallSet<const Use *, Threshold> Visited;
  220. int Count = 0;
  221. for (const Use &U : V->uses()) {
  222. // If there are lots of uses, conservatively say that the value
  223. // is captured to avoid taking too much compile time.
  224. if (Count++ >= Threshold)
  225. return Tracker->tooManyUses();
  226. if (!Tracker->shouldExplore(&U)) continue;
  227. Visited.insert(&U);
  228. Worklist.push_back(&U);
  229. }
  230. while (!Worklist.empty()) {
  231. const Use *U = Worklist.pop_back_val();
  232. Instruction *I = cast<Instruction>(U->getUser());
  233. V = U->get();
  234. switch (I->getOpcode()) {
  235. case Instruction::Call:
  236. case Instruction::Invoke: {
  237. CallSite CS(I);
  238. // Not captured if the callee is readonly, doesn't return a copy through
  239. // its return value and doesn't unwind (a readonly function can leak bits
  240. // by throwing an exception or not depending on the input value).
  241. if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
  242. break;
  243. // Not captured if only passed via 'nocapture' arguments. Note that
  244. // calling a function pointer does not in itself cause the pointer to
  245. // be captured. This is a subtle point considering that (for example)
  246. // the callee might return its own address. It is analogous to saying
  247. // that loading a value from a pointer does not cause the pointer to be
  248. // captured, even though the loaded value might be the pointer itself
  249. // (think of self-referential objects).
  250. CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
  251. for (CallSite::arg_iterator A = B; A != E; ++A)
  252. if (A->get() == V && !CS.doesNotCapture(A - B))
  253. // The parameter is not marked 'nocapture' - captured.
  254. if (Tracker->captured(U))
  255. return;
  256. break;
  257. }
  258. case Instruction::Load:
  259. // Loading from a pointer does not cause it to be captured.
  260. break;
  261. case Instruction::VAArg:
  262. // "va-arg" from a pointer does not cause it to be captured.
  263. break;
  264. case Instruction::Store:
  265. if (V == I->getOperand(0))
  266. // Stored the pointer - conservatively assume it may be captured.
  267. if (Tracker->captured(U))
  268. return;
  269. // Storing to the pointee does not cause the pointer to be captured.
  270. break;
  271. case Instruction::BitCast:
  272. case Instruction::GetElementPtr:
  273. case Instruction::PHI:
  274. case Instruction::Select:
  275. case Instruction::AddrSpaceCast:
  276. // The original value is not captured via this if the new value isn't.
  277. Count = 0;
  278. for (Use &UU : I->uses()) {
  279. // If there are lots of uses, conservatively say that the value
  280. // is captured to avoid taking too much compile time.
  281. if (Count++ >= Threshold)
  282. return Tracker->tooManyUses();
  283. if (Visited.insert(&UU).second)
  284. if (Tracker->shouldExplore(&UU))
  285. Worklist.push_back(&UU);
  286. }
  287. break;
  288. case Instruction::ICmp:
  289. // Don't count comparisons of a no-alias return value against null as
  290. // captures. This allows us to ignore comparisons of malloc results
  291. // with null, for example.
  292. if (ConstantPointerNull *CPN =
  293. dyn_cast<ConstantPointerNull>(I->getOperand(1)))
  294. if (CPN->getType()->getAddressSpace() == 0)
  295. if (isNoAliasCall(V->stripPointerCasts()))
  296. break;
  297. // Otherwise, be conservative. There are crazy ways to capture pointers
  298. // using comparisons.
  299. if (Tracker->captured(U))
  300. return;
  301. break;
  302. default:
  303. // Something else - be conservative and say it is captured.
  304. if (Tracker->captured(U))
  305. return;
  306. break;
  307. }
  308. }
  309. // All uses examined.
  310. }