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/CaptureTracking.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/IR/CallSite.h"
25 #include "llvm/IR/Constants.h"
26 #include "llvm/IR/Dominators.h"
27 #include "llvm/IR/Instructions.h"
31 CaptureTracker::~CaptureTracker() {}
33 bool CaptureTracker::shouldExplore(const Use *U) { return true; }
36 struct SimpleCaptureTracker : public CaptureTracker {
37 explicit SimpleCaptureTracker(bool ReturnCaptures)
38 : ReturnCaptures(ReturnCaptures), Captured(false) {}
40 void tooManyUses() override { Captured = true; }
42 bool captured(const Use *U) override {
43 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
55 /// Only find pointer captures which happen before the given instruction. Uses
56 /// the dominator tree to determine whether one instruction is before another.
57 /// Only support the case where the Value is defined in the same basic block
58 /// as the given instruction and the use.
59 struct CapturesBefore : public CaptureTracker {
60 CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT)
61 : BeforeHere(I), DT(DT), ReturnCaptures(ReturnCaptures),
64 void tooManyUses() override { Captured = true; }
66 bool shouldExplore(const Use *U) override {
67 Instruction *I = cast<Instruction>(U->getUser());
68 BasicBlock *BB = I->getParent();
69 // We explore this usage only if the usage can reach "BeforeHere".
70 // If use is not reachable from entry, there is no need to explore.
71 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
73 // If the value is defined in the same basic block as use and BeforeHere,
74 // there is no need to explore the use if BeforeHere dominates use.
75 // Check whether there is a path from I to BeforeHere.
76 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
77 !isPotentiallyReachable(I, BeforeHere, DT))
82 bool captured(const Use *U) override {
83 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
86 Instruction *I = cast<Instruction>(U->getUser());
87 BasicBlock *BB = I->getParent();
88 // Same logic as in shouldExplore.
89 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
91 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
92 !isPotentiallyReachable(I, BeforeHere, DT))
98 const Instruction *BeforeHere;
107 /// PointerMayBeCaptured - Return true if this pointer value may be captured
108 /// by the enclosing function (which is required to exist). This routine can
109 /// be expensive, so consider caching the results. The boolean ReturnCaptures
110 /// specifies whether returning the value (or part of it) from the function
111 /// counts as capturing it or not. The boolean StoreCaptures specified whether
112 /// storing the value (or part of it) into memory anywhere automatically
113 /// counts as capturing it or not.
114 bool llvm::PointerMayBeCaptured(const Value *V,
115 bool ReturnCaptures, bool StoreCaptures) {
116 assert(!isa<GlobalValue>(V) &&
117 "It doesn't make sense to ask whether a global is captured.");
119 // TODO: If StoreCaptures is not true, we could do Fancy analysis
120 // to determine whether this store is not actually an escape point.
121 // In that case, BasicAliasAnalysis should be updated as well to
122 // take advantage of this.
125 SimpleCaptureTracker SCT(ReturnCaptures);
126 PointerMayBeCaptured(V, &SCT);
130 /// PointerMayBeCapturedBefore - Return true if this pointer value may be
131 /// captured by the enclosing function (which is required to exist). If a
132 /// DominatorTree is provided, only captures which happen before the given
133 /// instruction are considered. This routine can be expensive, so consider
134 /// caching the results. The boolean ReturnCaptures specifies whether
135 /// returning the value (or part of it) from the function counts as capturing
136 /// it or not. The boolean StoreCaptures specified whether storing the value
137 /// (or part of it) into memory anywhere automatically counts as capturing it
139 bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
140 bool StoreCaptures, const Instruction *I,
142 assert(!isa<GlobalValue>(V) &&
143 "It doesn't make sense to ask whether a global is captured.");
146 return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
148 // TODO: See comment in PointerMayBeCaptured regarding what could be done
149 // with StoreCaptures.
151 CapturesBefore CB(ReturnCaptures, I, DT);
152 PointerMayBeCaptured(V, &CB);
156 /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
157 /// a cache. Then we can move the code from BasicAliasAnalysis into
158 /// that path, and remove this threshold.
159 static int const Threshold = 20;
161 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
162 assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
163 SmallVector<const Use *, Threshold> Worklist;
164 SmallSet<const Use *, Threshold> Visited;
167 for (const Use &U : V->uses()) {
168 // If there are lots of uses, conservatively say that the value
169 // is captured to avoid taking too much compile time.
170 if (Count++ >= Threshold)
171 return Tracker->tooManyUses();
173 if (!Tracker->shouldExplore(&U)) continue;
175 Worklist.push_back(&U);
178 while (!Worklist.empty()) {
179 const Use *U = Worklist.pop_back_val();
180 Instruction *I = cast<Instruction>(U->getUser());
183 switch (I->getOpcode()) {
184 case Instruction::Call:
185 case Instruction::Invoke: {
187 // Not captured if the callee is readonly, doesn't return a copy through
188 // its return value and doesn't unwind (a readonly function can leak bits
189 // by throwing an exception or not depending on the input value).
190 if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
193 // Not captured if only passed via 'nocapture' arguments. Note that
194 // calling a function pointer does not in itself cause the pointer to
195 // be captured. This is a subtle point considering that (for example)
196 // the callee might return its own address. It is analogous to saying
197 // that loading a value from a pointer does not cause the pointer to be
198 // captured, even though the loaded value might be the pointer itself
199 // (think of self-referential objects).
200 CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
201 for (CallSite::arg_iterator A = B; A != E; ++A)
202 if (A->get() == V && !CS.doesNotCapture(A - B))
203 // The parameter is not marked 'nocapture' - captured.
204 if (Tracker->captured(U))
208 case Instruction::Load:
209 // Loading from a pointer does not cause it to be captured.
211 case Instruction::VAArg:
212 // "va-arg" from a pointer does not cause it to be captured.
214 case Instruction::Store:
215 if (V == I->getOperand(0))
216 // Stored the pointer - conservatively assume it may be captured.
217 if (Tracker->captured(U))
219 // Storing to the pointee does not cause the pointer to be captured.
221 case Instruction::BitCast:
222 case Instruction::GetElementPtr:
223 case Instruction::PHI:
224 case Instruction::Select:
225 case Instruction::AddrSpaceCast:
226 // The original value is not captured via this if the new value isn't.
228 for (Use &UU : I->uses()) {
229 // If there are lots of uses, conservatively say that the value
230 // is captured to avoid taking too much compile time.
231 if (Count++ >= Threshold)
232 return Tracker->tooManyUses();
234 if (Visited.insert(&UU))
235 if (Tracker->shouldExplore(&UU))
236 Worklist.push_back(&UU);
239 case Instruction::ICmp:
240 // Don't count comparisons of a no-alias return value against null as
241 // captures. This allows us to ignore comparisons of malloc results
242 // with null, for example.
243 if (ConstantPointerNull *CPN =
244 dyn_cast<ConstantPointerNull>(I->getOperand(1)))
245 if (CPN->getType()->getAddressSpace() == 0)
246 if (isNoAliasCall(V->stripPointerCasts()))
248 // Otherwise, be conservative. There are crazy ways to capture pointers
249 // using comparisons.
250 if (Tracker->captured(U))
254 // Something else - be conservative and say it is captured.
255 if (Tracker->captured(U))
261 // All uses examined.