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 
19 #include "llvm/Analysis/CaptureTracking.h"
20 #include "llvm/ADT/SmallSet.h"
21 #include "llvm/ADT/SmallVector.h"
22 #include "llvm/Analysis/AliasAnalysis.h"
23 #include "llvm/Analysis/CFG.h"
24 #include "llvm/Analysis/OrderedBasicBlock.h"
25 #include "llvm/Analysis/ValueTracking.h"
26 #include "llvm/IR/CallSite.h"
27 #include "llvm/IR/Constants.h"
28 #include "llvm/IR/Dominators.h"
29 #include "llvm/IR/Instructions.h"
30 #include "llvm/IR/IntrinsicInst.h"
31 
32 using namespace llvm;
33 
34 CaptureTracker::~CaptureTracker() {}
35 
36 bool CaptureTracker::shouldExplore(const Use *U) { return true; }
37 
38 namespace {
39   struct SimpleCaptureTracker : public CaptureTracker {
40     explicit SimpleCaptureTracker(bool ReturnCaptures)
41       : ReturnCaptures(ReturnCaptures), Captured(false) {}
42 
43     void tooManyUses() override { Captured = true; }
44 
45     bool captured(const Use *U) override {
46       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
47         return false;
48 
49       Captured = true;
50       return true;
51     }
52 
53     bool ReturnCaptures;
54 
55     bool Captured;
56   };
57 
58   /// Only find pointer captures which happen before the given instruction. Uses
59   /// the dominator tree to determine whether one instruction is before another.
60   /// Only support the case where the Value is defined in the same basic block
61   /// as the given instruction and the use.
62   struct CapturesBefore : public CaptureTracker {
63 
64     CapturesBefore(bool ReturnCaptures, const Instruction *I, const DominatorTree *DT,
65                    bool IncludeI, OrderedBasicBlock *IC)
66       : OrderedBB(IC), BeforeHere(I), DT(DT),
67         ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {}
68 
69     void tooManyUses() override { Captured = true; }
70 
71     bool isSafeToPrune(Instruction *I) {
72       BasicBlock *BB = I->getParent();
73       // We explore this usage only if the usage can reach "BeforeHere".
74       // If use is not reachable from entry, there is no need to explore.
75       if (BeforeHere != I && !DT->isReachableFromEntry(BB))
76         return true;
77 
78       // Compute the case where both instructions are inside the same basic
79       // block. Since instructions in the same BB as BeforeHere are numbered in
80       // 'OrderedBB', avoid using 'dominates' and 'isPotentiallyReachable'
81       // which are very expensive for large basic blocks.
82       if (BB == BeforeHere->getParent()) {
83         // 'I' dominates 'BeforeHere' => not safe to prune.
84         //
85         // The value defined by an invoke dominates an instruction only
86         // if it dominates every instruction in UseBB. A PHI is dominated only
87         // if the instruction dominates every possible use in the UseBB. Since
88         // UseBB == BB, avoid pruning.
89         if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I) || I == BeforeHere)
90           return false;
91         if (!OrderedBB->dominates(BeforeHere, I))
92           return false;
93 
94         // 'BeforeHere' comes before 'I', it's safe to prune if we also
95         // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or
96         // by its successors, i.e, prune if:
97         //
98         //  (1) BB is an entry block or have no successors.
99         //  (2) There's no path coming back through BB successors.
100         if (BB == &BB->getParent()->getEntryBlock() ||
101             !BB->getTerminator()->getNumSuccessors())
102           return true;
103 
104         SmallVector<BasicBlock*, 32> Worklist;
105         Worklist.append(succ_begin(BB), succ_end(BB));
106         return !isPotentiallyReachableFromMany(Worklist, BB, DT);
107       }
108 
109       // If the value is defined in the same basic block as use and BeforeHere,
110       // there is no need to explore the use if BeforeHere dominates use.
111       // Check whether there is a path from I to BeforeHere.
112       if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
113           !isPotentiallyReachable(I, BeforeHere, DT))
114         return true;
115 
116       return false;
117     }
118 
119     bool shouldExplore(const Use *U) override {
120       Instruction *I = cast<Instruction>(U->getUser());
121 
122       if (BeforeHere == I && !IncludeI)
123         return false;
124 
125       if (isSafeToPrune(I))
126         return false;
127 
128       return true;
129     }
130 
131     bool captured(const Use *U) override {
132       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
133         return false;
134 
135       if (!shouldExplore(U))
136         return false;
137 
138       Captured = true;
139       return true;
140     }
141 
142     OrderedBasicBlock *OrderedBB;
143     const Instruction *BeforeHere;
144     const DominatorTree *DT;
145 
146     bool ReturnCaptures;
147     bool IncludeI;
148 
149     bool Captured;
150   };
151 }
152 
153 /// PointerMayBeCaptured - Return true if this pointer value may be captured
154 /// by the enclosing function (which is required to exist).  This routine can
155 /// be expensive, so consider caching the results.  The boolean ReturnCaptures
156 /// specifies whether returning the value (or part of it) from the function
157 /// counts as capturing it or not.  The boolean StoreCaptures specified whether
158 /// storing the value (or part of it) into memory anywhere automatically
159 /// counts as capturing it or not.
160 bool llvm::PointerMayBeCaptured(const Value *V,
161                                 bool ReturnCaptures, bool StoreCaptures,
162                                 unsigned MaxUsesToExplore) {
163   assert(!isa<GlobalValue>(V) &&
164          "It doesn't make sense to ask whether a global is captured.");
165 
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.
170   (void)StoreCaptures;
171 
172   SimpleCaptureTracker SCT(ReturnCaptures);
173   PointerMayBeCaptured(V, &SCT, MaxUsesToExplore);
174   return SCT.Captured;
175 }
176 
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                                       const DominatorTree *DT, bool IncludeI,
190                                       OrderedBasicBlock *OBB,
191                                       unsigned MaxUsesToExplore) {
192   assert(!isa<GlobalValue>(V) &&
193          "It doesn't make sense to ask whether a global is captured.");
194   bool UseNewOBB = OBB == nullptr;
195 
196   if (!DT)
197     return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures,
198                                 MaxUsesToExplore);
199   if (UseNewOBB)
200     OBB = new OrderedBasicBlock(I->getParent());
201 
202   // TODO: See comment in PointerMayBeCaptured regarding what could be done
203   // with StoreCaptures.
204 
205   CapturesBefore CB(ReturnCaptures, I, DT, IncludeI, OBB);
206   PointerMayBeCaptured(V, &CB, MaxUsesToExplore);
207 
208   if (UseNewOBB)
209     delete OBB;
210   return CB.Captured;
211 }
212 
213 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker,
214                                 unsigned MaxUsesToExplore) {
215   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
216   SmallVector<const Use *, DefaultMaxUsesToExplore> Worklist;
217   SmallSet<const Use *, DefaultMaxUsesToExplore> Visited;
218 
219   auto AddUses = [&](const Value *V) {
220     unsigned 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++ >= MaxUsesToExplore)
225         return Tracker->tooManyUses();
226       if (!Visited.insert(&U).second)
227         continue;
228       if (!Tracker->shouldExplore(&U))
229         continue;
230       Worklist.push_back(&U);
231     }
232   };
233   AddUses(V);
234 
235   while (!Worklist.empty()) {
236     const Use *U = Worklist.pop_back_val();
237     Instruction *I = cast<Instruction>(U->getUser());
238     V = U->get();
239 
240     switch (I->getOpcode()) {
241     case Instruction::Call:
242     case Instruction::Invoke: {
243       CallSite CS(I);
244       // Not captured if the callee is readonly, doesn't return a copy through
245       // its return value and doesn't unwind (a readonly function can leak bits
246       // by throwing an exception or not depending on the input value).
247       if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
248         break;
249 
250       // The pointer is not captured if returned pointer is not captured.
251       // NOTE: CaptureTracking users should not assume that only functions
252       // marked with nocapture do not capture. This means that places like
253       // GetUnderlyingObject in ValueTracking or DecomposeGEPExpression
254       // in BasicAA also need to know about this property.
255       if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(CS)) {
256         AddUses(I);
257         break;
258       }
259 
260       // Volatile operations effectively capture the memory location that they
261       // load and store to.
262       if (auto *MI = dyn_cast<MemIntrinsic>(I))
263         if (MI->isVolatile())
264           if (Tracker->captured(U))
265             return;
266 
267       // Not captured if only passed via 'nocapture' arguments.  Note that
268       // calling a function pointer does not in itself cause the pointer to
269       // be captured.  This is a subtle point considering that (for example)
270       // the callee might return its own address.  It is analogous to saying
271       // that loading a value from a pointer does not cause the pointer to be
272       // captured, even though the loaded value might be the pointer itself
273       // (think of self-referential objects).
274       CallSite::data_operand_iterator B =
275         CS.data_operands_begin(), E = CS.data_operands_end();
276       for (CallSite::data_operand_iterator A = B; A != E; ++A)
277         if (A->get() == V && !CS.doesNotCapture(A - B))
278           // The parameter is not marked 'nocapture' - captured.
279           if (Tracker->captured(U))
280             return;
281       break;
282     }
283     case Instruction::Load:
284       // Volatile loads make the address observable.
285       if (cast<LoadInst>(I)->isVolatile())
286         if (Tracker->captured(U))
287           return;
288       break;
289     case Instruction::VAArg:
290       // "va-arg" from a pointer does not cause it to be captured.
291       break;
292     case Instruction::Store:
293         // Stored the pointer - conservatively assume it may be captured.
294         // Volatile stores make the address observable.
295       if (V == I->getOperand(0) || cast<StoreInst>(I)->isVolatile())
296         if (Tracker->captured(U))
297           return;
298       break;
299     case Instruction::AtomicRMW: {
300       // atomicrmw conceptually includes both a load and store from
301       // the same location.
302       // As with a store, the location being accessed is not captured,
303       // but the value being stored is.
304       // Volatile stores make the address observable.
305       auto *ARMWI = cast<AtomicRMWInst>(I);
306       if (ARMWI->getValOperand() == V || ARMWI->isVolatile())
307         if (Tracker->captured(U))
308           return;
309       break;
310     }
311     case Instruction::AtomicCmpXchg: {
312       // cmpxchg conceptually includes both a load and store from
313       // the same location.
314       // As with a store, the location being accessed is not captured,
315       // but the value being stored is.
316       // Volatile stores make the address observable.
317       auto *ACXI = cast<AtomicCmpXchgInst>(I);
318       if (ACXI->getCompareOperand() == V || ACXI->getNewValOperand() == V ||
319           ACXI->isVolatile())
320         if (Tracker->captured(U))
321           return;
322       break;
323     }
324     case Instruction::BitCast:
325     case Instruction::GetElementPtr:
326     case Instruction::PHI:
327     case Instruction::Select:
328     case Instruction::AddrSpaceCast:
329       // The original value is not captured via this if the new value isn't.
330       AddUses(I);
331       break;
332     case Instruction::ICmp: {
333       // Don't count comparisons of a no-alias return value against null as
334       // captures. This allows us to ignore comparisons of malloc results
335       // with null, for example.
336       if (ConstantPointerNull *CPN =
337           dyn_cast<ConstantPointerNull>(I->getOperand(1)))
338         if (CPN->getType()->getAddressSpace() == 0)
339           if (isNoAliasCall(V->stripPointerCasts()))
340             break;
341       // Comparison against value stored in global variable. Given the pointer
342       // does not escape, its value cannot be guessed and stored separately in a
343       // global variable.
344       unsigned OtherIndex = (I->getOperand(0) == V) ? 1 : 0;
345       auto *LI = dyn_cast<LoadInst>(I->getOperand(OtherIndex));
346       if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
347         break;
348       // Otherwise, be conservative. There are crazy ways to capture pointers
349       // using comparisons.
350       if (Tracker->captured(U))
351         return;
352       break;
353     }
354     default:
355       // Something else - be conservative and say it is captured.
356       if (Tracker->captured(U))
357         return;
358       break;
359     }
360   }
361 
362   // All uses examined.
363 }
364