1 //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
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.
17 //===----------------------------------------------------------------------===//
19 #include "llvm/ADT/SmallSet.h"
20 #include "llvm/ADT/SmallVector.h"
21 #include "llvm/Analysis/AliasAnalysis.h"
22 #include "llvm/Analysis/CFG.h"
23 #include "llvm/Analysis/CaptureTracking.h"
24 #include "llvm/Analysis/OrderedBasicBlock.h"
25 #include "llvm/IR/CallSite.h"
26 #include "llvm/IR/Constants.h"
27 #include "llvm/IR/Dominators.h"
28 #include "llvm/IR/Instructions.h"
32 CaptureTracker::~CaptureTracker() {}
34 bool CaptureTracker::shouldExplore(const Use *U) { return true; }
37 struct SimpleCaptureTracker : public CaptureTracker {
38 explicit SimpleCaptureTracker(bool ReturnCaptures)
39 : ReturnCaptures(ReturnCaptures), Captured(false) {}
41 void tooManyUses() override { Captured = true; }
43 bool captured(const Use *U) override {
44 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
56 /// Only find pointer captures which happen before the given instruction. Uses
57 /// the dominator tree to determine whether one instruction is before another.
58 /// Only support the case where the Value is defined in the same basic block
59 /// as the given instruction and the use.
60 struct CapturesBefore : public CaptureTracker {
62 CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT,
63 bool IncludeI, OrderedBasicBlock *IC)
64 : OrderedBB(IC), BeforeHere(I), DT(DT),
65 ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {}
67 void tooManyUses() override { Captured = true; }
69 bool isSafeToPrune(Instruction *I) {
70 BasicBlock *BB = I->getParent();
71 // We explore this usage only if the usage can reach "BeforeHere".
72 // If use is not reachable from entry, there is no need to explore.
73 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
76 // Compute the case where both instructions are inside the same basic
77 // block. Since instructions in the same BB as BeforeHere are numbered in
78 // 'OrderedBB', avoid using 'dominates' and 'isPotentiallyReachable'
79 // which are very expensive for large basic blocks.
80 if (BB == BeforeHere->getParent()) {
81 // 'I' dominates 'BeforeHere' => not safe to prune.
83 // The value defined by an invoke dominates an instruction only if it
84 // dominates every instruction in UseBB. A PHI is dominated only if
85 // the instruction dominates every possible use in the UseBB. Since
86 // UseBB == BB, avoid pruning.
87 if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I) || I == BeforeHere)
89 if (!OrderedBB->dominates(BeforeHere, I))
92 // 'BeforeHere' comes before 'I', it's safe to prune if we also
93 // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or
94 // by its successors, i.e, prune if:
96 // (1) BB is an entry block or have no sucessors.
97 // (2) There's no path coming back through BB sucessors.
98 if (BB == &BB->getParent()->getEntryBlock() ||
99 !BB->getTerminator()->getNumSuccessors())
102 SmallVector<BasicBlock*, 32> Worklist;
103 Worklist.append(succ_begin(BB), succ_end(BB));
104 if (!isPotentiallyReachableFromMany(Worklist, BB, DT))
110 // If the value is defined in the same basic block as use and BeforeHere,
111 // there is no need to explore the use if BeforeHere dominates use.
112 // Check whether there is a path from I to BeforeHere.
113 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
114 !isPotentiallyReachable(I, BeforeHere, DT))
120 bool shouldExplore(const Use *U) override {
121 Instruction *I = cast<Instruction>(U->getUser());
123 if (BeforeHere == I && !IncludeI)
126 if (isSafeToPrune(I))
132 bool captured(const Use *U) override {
133 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
136 if (!shouldExplore(U))
143 OrderedBasicBlock *OrderedBB;
144 const Instruction *BeforeHere;
154 /// PointerMayBeCaptured - Return true if this pointer value may be captured
155 /// by the enclosing function (which is required to exist). This routine can
156 /// be expensive, so consider caching the results. The boolean ReturnCaptures
157 /// specifies whether returning the value (or part of it) from the function
158 /// counts as capturing it or not. The boolean StoreCaptures specified whether
159 /// storing the value (or part of it) into memory anywhere automatically
160 /// counts as capturing it or not.
161 bool llvm::PointerMayBeCaptured(const Value *V,
162 bool ReturnCaptures, bool StoreCaptures) {
163 assert(!isa<GlobalValue>(V) &&
164 "It doesn't make sense to ask whether a global is captured.");
166 // TODO: If StoreCaptures is not true, we could do Fancy analysis
167 // to determine whether this store is not actually an escape point.
168 // In that case, BasicAliasAnalysis should be updated as well to
169 // take advantage of this.
172 SimpleCaptureTracker SCT(ReturnCaptures);
173 PointerMayBeCaptured(V, &SCT);
177 /// PointerMayBeCapturedBefore - Return true if this pointer value may be
178 /// captured by the enclosing function (which is required to exist). If a
179 /// DominatorTree is provided, only captures which happen before the given
180 /// instruction are considered. This routine can be expensive, so consider
181 /// caching the results. The boolean ReturnCaptures specifies whether
182 /// returning the value (or part of it) from the function counts as capturing
183 /// it or not. The boolean StoreCaptures specified whether storing the value
184 /// (or part of it) into memory anywhere automatically counts as capturing it
185 /// or not. A ordered basic block \p OBB can be used in order to speed up
186 /// queries about relative order among instructions in the same basic block.
187 bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
188 bool StoreCaptures, const Instruction *I,
189 DominatorTree *DT, bool IncludeI,
190 OrderedBasicBlock *OBB) {
191 assert(!isa<GlobalValue>(V) &&
192 "It doesn't make sense to ask whether a global is captured.");
193 bool UseNewOBB = OBB == nullptr;
196 return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
198 OBB = new OrderedBasicBlock(I->getParent());
200 // TODO: See comment in PointerMayBeCaptured regarding what could be done
201 // with StoreCaptures.
203 CapturesBefore CB(ReturnCaptures, I, DT, IncludeI, OBB);
204 PointerMayBeCaptured(V, &CB);
211 /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
212 /// a cache. Then we can move the code from BasicAliasAnalysis into
213 /// that path, and remove this threshold.
214 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;
222 for (const Use &U : V->uses()) {
223 // If there are lots of uses, conservatively say that the value
224 // is captured to avoid taking too much compile time.
225 if (Count++ >= Threshold)
226 return Tracker->tooManyUses();
228 if (!Tracker->shouldExplore(&U)) continue;
230 Worklist.push_back(&U);
233 while (!Worklist.empty()) {
234 const Use *U = Worklist.pop_back_val();
235 Instruction *I = cast<Instruction>(U->getUser());
238 switch (I->getOpcode()) {
239 case Instruction::Call:
240 case Instruction::Invoke: {
242 // Not captured if the callee is readonly, doesn't return a copy through
243 // its return value and doesn't unwind (a readonly function can leak bits
244 // by throwing an exception or not depending on the input value).
245 if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
248 // Not captured if only passed via 'nocapture' arguments. Note that
249 // calling a function pointer does not in itself cause the pointer to
250 // be captured. This is a subtle point considering that (for example)
251 // the callee might return its own address. It is analogous to saying
252 // that loading a value from a pointer does not cause the pointer to be
253 // captured, even though the loaded value might be the pointer itself
254 // (think of self-referential objects).
255 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
256 for (CallSite::arg_iterator A = B; A != E; ++A)
257 if (A->get() == V && !CS.doesNotCapture(A - B))
258 // The parameter is not marked 'nocapture' - captured.
259 if (Tracker->captured(U))
263 case Instruction::Load:
264 // Loading from a pointer does not cause it to be captured.
266 case Instruction::VAArg:
267 // "va-arg" from a pointer does not cause it to be captured.
269 case Instruction::Store:
270 if (V == I->getOperand(0))
271 // Stored the pointer - conservatively assume it may be captured.
272 if (Tracker->captured(U))
274 // Storing to the pointee does not cause the pointer to be captured.
276 case Instruction::BitCast:
277 case Instruction::GetElementPtr:
278 case Instruction::PHI:
279 case Instruction::Select:
280 case Instruction::AddrSpaceCast:
281 // The original value is not captured via this if the new value isn't.
283 for (Use &UU : I->uses()) {
284 // If there are lots of uses, conservatively say that the value
285 // is captured to avoid taking too much compile time.
286 if (Count++ >= Threshold)
287 return Tracker->tooManyUses();
289 if (Visited.insert(&UU).second)
290 if (Tracker->shouldExplore(&UU))
291 Worklist.push_back(&UU);
294 case Instruction::ICmp:
295 // Don't count comparisons of a no-alias return value against null as
296 // captures. This allows us to ignore comparisons of malloc results
297 // with null, for example.
298 if (ConstantPointerNull *CPN =
299 dyn_cast<ConstantPointerNull>(I->getOperand(1)))
300 if (CPN->getType()->getAddressSpace() == 0)
301 if (isNoAliasCall(V->stripPointerCasts()))
303 // Otherwise, be conservative. There are crazy ways to capture pointers
304 // using comparisons.
305 if (Tracker->captured(U))
309 // Something else - be conservative and say it is captured.
310 if (Tracker->captured(U))
316 // All uses examined.