blob: 3b0026ba10e90bd9308ff7e154f14476748ef8a2 [file] [log] [blame]
Duncan Sandse0aa0d62009-01-18 12:19:30 +00001//===--- 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
Chandler Carruth6bda14b2017-06-06 11:49:48 +000019#include "llvm/Analysis/CaptureTracking.h"
Jakub Staszak173bce32012-01-17 22:16:31 +000020#include "llvm/ADT/SmallSet.h"
21#include "llvm/ADT/SmallVector.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000022#include "llvm/Analysis/AliasAnalysis.h"
Hal Finkelb0356212014-07-21 13:15:48 +000023#include "llvm/Analysis/CFG.h"
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +000024#include "llvm/Analysis/OrderedBasicBlock.h"
Chandler Carruth219b89b2014-03-04 11:01:28 +000025#include "llvm/IR/CallSite.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000026#include "llvm/IR/Constants.h"
Hal Finkelb0356212014-07-21 13:15:48 +000027#include "llvm/IR/Dominators.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000028#include "llvm/IR/Instructions.h"
David Majnemer7f324202016-05-26 17:36:22 +000029#include "llvm/IR/IntrinsicInst.h"
Jakub Staszakc733bf22013-03-10 00:34:01 +000030
Duncan Sandse0aa0d62009-01-18 12:19:30 +000031using namespace llvm;
32
Nick Lewyckyaa2a00d2011-11-21 18:32:21 +000033CaptureTracker::~CaptureTracker() {}
34
Chandler Carruth64e9aa52014-03-05 10:21:48 +000035bool CaptureTracker::shouldExplore(const Use *U) { return true; }
Nick Lewycky7c3b5d92012-10-08 22:12:48 +000036
Nick Lewycky7013a192011-11-14 22:49:42 +000037namespace {
Nick Lewycky6ae03c32011-11-20 19:37:06 +000038 struct SimpleCaptureTracker : public CaptureTracker {
Nick Lewycky7013a192011-11-14 22:49:42 +000039 explicit SimpleCaptureTracker(bool ReturnCaptures)
40 : ReturnCaptures(ReturnCaptures), Captured(false) {}
41
Craig Toppere9ba7592014-03-05 07:30:04 +000042 void tooManyUses() override { Captured = true; }
Nick Lewycky7013a192011-11-14 22:49:42 +000043
Chandler Carruth64e9aa52014-03-05 10:21:48 +000044 bool captured(const Use *U) override {
Nick Lewycky4c378a42011-12-28 23:24:21 +000045 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
Chad Rosier8244b1d2012-05-10 23:38:07 +000046 return false;
Nick Lewycky7013a192011-11-14 22:49:42 +000047
48 Captured = true;
49 return true;
50 }
51
52 bool ReturnCaptures;
53
54 bool Captured;
55 };
Hal Finkelb0356212014-07-21 13:15:48 +000056
57 /// Only find pointer captures which happen before the given instruction. Uses
58 /// the dominator tree to determine whether one instruction is before another.
59 /// Only support the case where the Value is defined in the same basic block
60 /// as the given instruction and the use.
61 struct CapturesBefore : public CaptureTracker {
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000062
Hal Finkeld32803b2014-07-21 21:30:22 +000063 CapturesBefore(bool ReturnCaptures, const Instruction *I, DominatorTree *DT,
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +000064 bool IncludeI, OrderedBasicBlock *IC)
65 : OrderedBB(IC), BeforeHere(I), DT(DT),
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000066 ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {}
Hal Finkelb0356212014-07-21 13:15:48 +000067
68 void tooManyUses() override { Captured = true; }
69
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000070 bool isSafeToPrune(Instruction *I) {
Hal Finkelb0356212014-07-21 13:15:48 +000071 BasicBlock *BB = I->getParent();
72 // We explore this usage only if the usage can reach "BeforeHere".
73 // If use is not reachable from entry, there is no need to explore.
74 if (BeforeHere != I && !DT->isReachableFromEntry(BB))
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000075 return true;
76
77 // Compute the case where both instructions are inside the same basic
78 // block. Since instructions in the same BB as BeforeHere are numbered in
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +000079 // 'OrderedBB', avoid using 'dominates' and 'isPotentiallyReachable'
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000080 // which are very expensive for large basic blocks.
81 if (BB == BeforeHere->getParent()) {
82 // 'I' dominates 'BeforeHere' => not safe to prune.
83 //
David Majnemer8a1c45d2015-12-12 05:38:55 +000084 // The value defined by an invoke dominates an instruction only
David Majnemer0bc0eef2015-08-15 02:46:08 +000085 // if it dominates every instruction in UseBB. A PHI is dominated only
86 // if the instruction dominates every possible use in the UseBB. Since
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000087 // UseBB == BB, avoid pruning.
David Majnemer8a1c45d2015-12-12 05:38:55 +000088 if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I) || I == BeforeHere)
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000089 return false;
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +000090 if (!OrderedBB->dominates(BeforeHere, I))
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000091 return false;
92
93 // 'BeforeHere' comes before 'I', it's safe to prune if we also
94 // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or
95 // by its successors, i.e, prune if:
96 //
Hiroshi Inoue713b5ba2017-07-09 05:54:44 +000097 // (1) BB is an entry block or have no successors.
98 // (2) There's no path coming back through BB successors.
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +000099 if (BB == &BB->getParent()->getEntryBlock() ||
100 !BB->getTerminator()->getNumSuccessors())
101 return true;
102
103 SmallVector<BasicBlock*, 32> Worklist;
104 Worklist.append(succ_begin(BB), succ_end(BB));
Alexander Kornienko484e48e32015-11-05 21:07:12 +0000105 return !isPotentiallyReachableFromMany(Worklist, BB, DT);
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000106 }
107
Hal Finkelb0356212014-07-21 13:15:48 +0000108 // If the value is defined in the same basic block as use and BeforeHere,
109 // there is no need to explore the use if BeforeHere dominates use.
110 // Check whether there is a path from I to BeforeHere.
111 if (BeforeHere != I && DT->dominates(BeforeHere, I) &&
112 !isPotentiallyReachable(I, BeforeHere, DT))
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000113 return true;
114
115 return false;
116 }
117
118 bool shouldExplore(const Use *U) override {
119 Instruction *I = cast<Instruction>(U->getUser());
120
121 if (BeforeHere == I && !IncludeI)
Hal Finkelb0356212014-07-21 13:15:48 +0000122 return false;
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000123
124 if (isSafeToPrune(I))
125 return false;
126
Hal Finkelb0356212014-07-21 13:15:48 +0000127 return true;
128 }
129
130 bool captured(const Use *U) override {
131 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
132 return false;
133
Bruno Cardoso Lopes7900ef82015-06-24 17:53:17 +0000134 if (!shouldExplore(U))
Hal Finkeld32803b2014-07-21 21:30:22 +0000135 return false;
136
Hal Finkelb0356212014-07-21 13:15:48 +0000137 Captured = true;
138 return true;
139 }
140
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000141 OrderedBasicBlock *OrderedBB;
Hal Finkelb0356212014-07-21 13:15:48 +0000142 const Instruction *BeforeHere;
143 DominatorTree *DT;
144
145 bool ReturnCaptures;
Hal Finkeld32803b2014-07-21 21:30:22 +0000146 bool IncludeI;
Hal Finkelb0356212014-07-21 13:15:48 +0000147
148 bool Captured;
149 };
Alexander Kornienkof00654e2015-06-23 09:49:53 +0000150}
Dan Gohman2d27b192009-12-08 23:59:12 +0000151
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000152/// PointerMayBeCaptured - Return true if this pointer value may be captured
153/// by the enclosing function (which is required to exist). This routine can
154/// be expensive, so consider caching the results. The boolean ReturnCaptures
155/// specifies whether returning the value (or part of it) from the function
Dan Gohman94e61762009-11-19 21:57:48 +0000156/// counts as capturing it or not. The boolean StoreCaptures specified whether
157/// storing the value (or part of it) into memory anywhere automatically
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000158/// counts as capturing it or not.
Dan Gohman94e61762009-11-19 21:57:48 +0000159bool llvm::PointerMayBeCaptured(const Value *V,
160 bool ReturnCaptures, bool StoreCaptures) {
Nick Lewycky063ae582011-11-21 19:42:56 +0000161 assert(!isa<GlobalValue>(V) &&
162 "It doesn't make sense to ask whether a global is captured.");
163
Nick Lewycky7013a192011-11-14 22:49:42 +0000164 // TODO: If StoreCaptures is not true, we could do Fancy analysis
165 // to determine whether this store is not actually an escape point.
166 // In that case, BasicAliasAnalysis should be updated as well to
167 // take advantage of this.
168 (void)StoreCaptures;
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000169
Nick Lewycky7013a192011-11-14 22:49:42 +0000170 SimpleCaptureTracker SCT(ReturnCaptures);
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000171 PointerMayBeCaptured(V, &SCT);
Nick Lewycky7013a192011-11-14 22:49:42 +0000172 return SCT.Captured;
Duncan Sandse0aa0d62009-01-18 12:19:30 +0000173}
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000174
Hal Finkelb0356212014-07-21 13:15:48 +0000175/// PointerMayBeCapturedBefore - Return true if this pointer value may be
176/// captured by the enclosing function (which is required to exist). If a
177/// DominatorTree is provided, only captures which happen before the given
178/// instruction are considered. This routine can be expensive, so consider
179/// caching the results. The boolean ReturnCaptures specifies whether
180/// returning the value (or part of it) from the function counts as capturing
181/// it or not. The boolean StoreCaptures specified whether storing the value
182/// (or part of it) into memory anywhere automatically counts as capturing it
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000183/// or not. A ordered basic block \p OBB can be used in order to speed up
184/// queries about relative order among instructions in the same basic block.
Hal Finkelb0356212014-07-21 13:15:48 +0000185bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
186 bool StoreCaptures, const Instruction *I,
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000187 DominatorTree *DT, bool IncludeI,
188 OrderedBasicBlock *OBB) {
Hal Finkelb0356212014-07-21 13:15:48 +0000189 assert(!isa<GlobalValue>(V) &&
190 "It doesn't make sense to ask whether a global is captured.");
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000191 bool UseNewOBB = OBB == nullptr;
Hal Finkelb0356212014-07-21 13:15:48 +0000192
193 if (!DT)
194 return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures);
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000195 if (UseNewOBB)
196 OBB = new OrderedBasicBlock(I->getParent());
Hal Finkelb0356212014-07-21 13:15:48 +0000197
198 // TODO: See comment in PointerMayBeCaptured regarding what could be done
199 // with StoreCaptures.
200
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000201 CapturesBefore CB(ReturnCaptures, I, DT, IncludeI, OBB);
Hal Finkelb0356212014-07-21 13:15:48 +0000202 PointerMayBeCaptured(V, &CB);
Bruno Cardoso Lopesdfc1d962015-07-31 14:31:35 +0000203
204 if (UseNewOBB)
205 delete OBB;
Hal Finkelb0356212014-07-21 13:15:48 +0000206 return CB.Captured;
207}
208
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000209/// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
210/// a cache. Then we can move the code from BasicAliasAnalysis into
211/// that path, and remove this threshold.
212static int const Threshold = 20;
213
214void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
215 assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
Chandler Carruth64e9aa52014-03-05 10:21:48 +0000216 SmallVector<const Use *, Threshold> Worklist;
217 SmallSet<const Use *, Threshold> Visited;
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000218 int Count = 0;
219
Chandler Carruthcdf47882014-03-09 03:16:01 +0000220 for (const Use &U : V->uses()) {
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000221 // If there are lots of uses, conservatively say that the value
222 // is captured to avoid taking too much compile time.
223 if (Count++ >= Threshold)
224 return Tracker->tooManyUses();
225
Chandler Carruthcdf47882014-03-09 03:16:01 +0000226 if (!Tracker->shouldExplore(&U)) continue;
227 Visited.insert(&U);
228 Worklist.push_back(&U);
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000229 }
230
231 while (!Worklist.empty()) {
Chandler Carruth64e9aa52014-03-05 10:21:48 +0000232 const Use *U = Worklist.pop_back_val();
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000233 Instruction *I = cast<Instruction>(U->getUser());
234 V = U->get();
235
236 switch (I->getOpcode()) {
237 case Instruction::Call:
238 case Instruction::Invoke: {
239 CallSite CS(I);
240 // Not captured if the callee is readonly, doesn't return a copy through
241 // its return value and doesn't unwind (a readonly function can leak bits
242 // by throwing an exception or not depending on the input value).
243 if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
244 break;
245
David Majnemer7f324202016-05-26 17:36:22 +0000246 // Volatile operations effectively capture the memory location that they
247 // load and store to.
248 if (auto *MI = dyn_cast<MemIntrinsic>(I))
249 if (MI->isVolatile())
250 if (Tracker->captured(U))
251 return;
252
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000253 // Not captured if only passed via 'nocapture' arguments. Note that
254 // calling a function pointer does not in itself cause the pointer to
255 // be captured. This is a subtle point considering that (for example)
256 // the callee might return its own address. It is analogous to saying
257 // that loading a value from a pointer does not cause the pointer to be
258 // captured, even though the loaded value might be the pointer itself
259 // (think of self-referential objects).
Sanjoy Dasea343822015-11-04 23:21:06 +0000260 CallSite::data_operand_iterator B =
261 CS.data_operands_begin(), E = CS.data_operands_end();
262 for (CallSite::data_operand_iterator A = B; A != E; ++A)
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000263 if (A->get() == V && !CS.doesNotCapture(A - B))
264 // The parameter is not marked 'nocapture' - captured.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000265 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000266 return;
267 break;
268 }
269 case Instruction::Load:
David Majnemer7f324202016-05-26 17:36:22 +0000270 // Volatile loads make the address observable.
271 if (cast<LoadInst>(I)->isVolatile())
272 if (Tracker->captured(U))
273 return;
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000274 break;
275 case Instruction::VAArg:
276 // "va-arg" from a pointer does not cause it to be captured.
277 break;
278 case Instruction::Store:
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000279 // Stored the pointer - conservatively assume it may be captured.
David Majnemer7f324202016-05-26 17:36:22 +0000280 // Volatile stores make the address observable.
281 if (V == I->getOperand(0) || cast<StoreInst>(I)->isVolatile())
Philip Reamesbd09e862016-02-18 19:23:27 +0000282 if (Tracker->captured(U))
283 return;
284 break;
David Majnemer7f324202016-05-26 17:36:22 +0000285 case Instruction::AtomicRMW: {
286 // atomicrmw conceptually includes both a load and store from
287 // the same location.
288 // As with a store, the location being accessed is not captured,
289 // but the value being stored is.
290 // Volatile stores make the address observable.
291 auto *ARMWI = cast<AtomicRMWInst>(I);
292 if (ARMWI->getValOperand() == V || ARMWI->isVolatile())
293 if (Tracker->captured(U))
294 return;
295 break;
296 }
297 case Instruction::AtomicCmpXchg: {
298 // cmpxchg conceptually includes both a load and store from
299 // the same location.
300 // As with a store, the location being accessed is not captured,
301 // but the value being stored is.
302 // Volatile stores make the address observable.
303 auto *ACXI = cast<AtomicCmpXchgInst>(I);
304 if (ACXI->getCompareOperand() == V || ACXI->getNewValOperand() == V ||
305 ACXI->isVolatile())
306 if (Tracker->captured(U))
307 return;
308 break;
309 }
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000310 case Instruction::BitCast:
311 case Instruction::GetElementPtr:
312 case Instruction::PHI:
313 case Instruction::Select:
Matt Arsenaulte55a2c22014-01-14 19:11:52 +0000314 case Instruction::AddrSpaceCast:
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000315 // The original value is not captured via this if the new value isn't.
Benjamin Kramerd2757ba2013-10-03 13:24:02 +0000316 Count = 0;
Chandler Carruthcdf47882014-03-09 03:16:01 +0000317 for (Use &UU : I->uses()) {
Benjamin Kramerd2757ba2013-10-03 13:24:02 +0000318 // If there are lots of uses, conservatively say that the value
319 // is captured to avoid taking too much compile time.
320 if (Count++ >= Threshold)
321 return Tracker->tooManyUses();
322
David Blaikie70573dc2014-11-19 07:49:26 +0000323 if (Visited.insert(&UU).second)
Chandler Carruthcdf47882014-03-09 03:16:01 +0000324 if (Tracker->shouldExplore(&UU))
325 Worklist.push_back(&UU);
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000326 }
327 break;
Anna Thomas43d7e1c2016-05-03 14:58:21 +0000328 case Instruction::ICmp: {
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000329 // Don't count comparisons of a no-alias return value against null as
330 // captures. This allows us to ignore comparisons of malloc results
331 // with null, for example.
Nick Lewyckyc2ec0722013-07-06 00:29:58 +0000332 if (ConstantPointerNull *CPN =
333 dyn_cast<ConstantPointerNull>(I->getOperand(1)))
334 if (CPN->getType()->getAddressSpace() == 0)
335 if (isNoAliasCall(V->stripPointerCasts()))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000336 break;
Anna Thomas43d7e1c2016-05-03 14:58:21 +0000337 // Comparison against value stored in global variable. Given the pointer
338 // does not escape, its value cannot be guessed and stored separately in a
339 // global variable.
340 unsigned OtherIndex = (I->getOperand(0) == V) ? 1 : 0;
341 auto *LI = dyn_cast<LoadInst>(I->getOperand(OtherIndex));
342 if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
343 break;
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000344 // Otherwise, be conservative. There are crazy ways to capture pointers
345 // using comparisons.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000346 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000347 return;
348 break;
Anna Thomas43d7e1c2016-05-03 14:58:21 +0000349 }
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000350 default:
351 // Something else - be conservative and say it is captured.
Nick Lewycky4c378a42011-12-28 23:24:21 +0000352 if (Tracker->captured(U))
Nick Lewycky6ae03c32011-11-20 19:37:06 +0000353 return;
354 break;
355 }
356 }
357
358 // All uses examined.
359}