1 //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file contains routines that help determine which pointers are captured. 10 // A pointer value is captured if the function makes a copy of any part of the 11 // pointer that outlives the call. Not being captured means, more or less, that 12 // the pointer is only dereferenced and not stored in a global. Returning part 13 // of the pointer as the function return value may or may not count as capturing 14 // the pointer, depending on the context. 15 // 16 //===----------------------------------------------------------------------===// 17 18 #include "llvm/Analysis/CaptureTracking.h" 19 #include "llvm/ADT/SmallSet.h" 20 #include "llvm/ADT/SmallVector.h" 21 #include "llvm/ADT/Statistic.h" 22 #include "llvm/Analysis/AliasAnalysis.h" 23 #include "llvm/Analysis/CFG.h" 24 #include "llvm/Analysis/ValueTracking.h" 25 #include "llvm/IR/Constants.h" 26 #include "llvm/IR/Dominators.h" 27 #include "llvm/IR/Instructions.h" 28 #include "llvm/IR/IntrinsicInst.h" 29 #include "llvm/Support/CommandLine.h" 30 31 using namespace llvm; 32 33 #define DEBUG_TYPE "capture-tracking" 34 35 STATISTIC(NumCaptured, "Number of pointers maybe captured"); 36 STATISTIC(NumNotCaptured, "Number of pointers not captured"); 37 STATISTIC(NumCapturedBefore, "Number of pointers maybe captured before"); 38 STATISTIC(NumNotCapturedBefore, "Number of pointers not captured before"); 39 40 /// The default value for MaxUsesToExplore argument. It's relatively small to 41 /// keep the cost of analysis reasonable for clients like BasicAliasAnalysis, 42 /// where the results can't be cached. 43 /// TODO: we should probably introduce a caching CaptureTracking analysis and 44 /// use it where possible. The caching version can use much higher limit or 45 /// don't have this cap at all. 46 static cl::opt<unsigned> 47 DefaultMaxUsesToExplore("capture-tracking-max-uses-to-explore", cl::Hidden, 48 cl::desc("Maximal number of uses to explore."), 49 cl::init(20)); 50 51 unsigned llvm::getDefaultMaxUsesToExploreForCaptureTracking() { 52 return DefaultMaxUsesToExplore; 53 } 54 55 CaptureTracker::~CaptureTracker() {} 56 57 bool CaptureTracker::shouldExplore(const Use *U) { return true; } 58 59 bool CaptureTracker::isDereferenceableOrNull(Value *O, const DataLayout &DL) { 60 // An inbounds GEP can either be a valid pointer (pointing into 61 // or to the end of an allocation), or be null in the default 62 // address space. So for an inbounds GEP there is no way to let 63 // the pointer escape using clever GEP hacking because doing so 64 // would make the pointer point outside of the allocated object 65 // and thus make the GEP result a poison value. Similarly, other 66 // dereferenceable pointers cannot be manipulated without producing 67 // poison. 68 if (auto *GEP = dyn_cast<GetElementPtrInst>(O)) 69 if (GEP->isInBounds()) 70 return true; 71 bool CanBeNull, CanBeFreed; 72 return O->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed); 73 } 74 75 namespace { 76 struct SimpleCaptureTracker : public CaptureTracker { 77 explicit SimpleCaptureTracker(bool ReturnCaptures) 78 : ReturnCaptures(ReturnCaptures), Captured(false) {} 79 80 void tooManyUses() override { Captured = true; } 81 82 bool captured(const Use *U) override { 83 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures) 84 return false; 85 86 Captured = true; 87 return true; 88 } 89 90 bool ReturnCaptures; 91 92 bool Captured; 93 }; 94 95 /// Only find pointer captures which happen before the given instruction. Uses 96 /// the dominator tree to determine whether one instruction is before another. 97 /// Only support the case where the Value is defined in the same basic block 98 /// as the given instruction and the use. 99 struct CapturesBefore : public CaptureTracker { 100 101 CapturesBefore(bool ReturnCaptures, const Instruction *I, const DominatorTree *DT, 102 bool IncludeI) 103 : BeforeHere(I), DT(DT), 104 ReturnCaptures(ReturnCaptures), IncludeI(IncludeI), Captured(false) {} 105 106 void tooManyUses() override { Captured = true; } 107 108 bool isSafeToPrune(Instruction *I) { 109 if (BeforeHere == I) 110 return !IncludeI; 111 112 BasicBlock *BB = I->getParent(); 113 // We explore this usage only if the usage can reach "BeforeHere". 114 // If use is not reachable from entry, there is no need to explore. 115 if (!DT->isReachableFromEntry(BB)) 116 return true; 117 118 // Compute the case where both instructions are inside the same basic 119 // block. 120 if (BB == BeforeHere->getParent()) { 121 // 'I' dominates 'BeforeHere' => not safe to prune. 122 // 123 // The value defined by an invoke dominates an instruction only 124 // if it dominates every instruction in UseBB. A PHI is dominated only 125 // if the instruction dominates every possible use in the UseBB. Since 126 // UseBB == BB, avoid pruning. 127 if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I)) 128 return false; 129 if (!BeforeHere->comesBefore(I)) 130 return false; 131 132 // 'BeforeHere' comes before 'I', it's safe to prune if we also 133 // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or 134 // by its successors, i.e, prune if: 135 // 136 // (1) BB is an entry block or have no successors. 137 // (2) There's no path coming back through BB successors. 138 if (BB->isEntryBlock() || !BB->getTerminator()->getNumSuccessors()) 139 return true; 140 141 SmallVector<BasicBlock*, 32> Worklist; 142 Worklist.append(succ_begin(BB), succ_end(BB)); 143 return !isPotentiallyReachableFromMany(Worklist, BB, nullptr, DT); 144 } 145 146 // Check whether there is a path from I to BeforeHere. 147 return !isPotentiallyReachable(I, BeforeHere, nullptr, DT); 148 } 149 150 bool captured(const Use *U) override { 151 Instruction *I = cast<Instruction>(U->getUser()); 152 if (isa<ReturnInst>(I) && !ReturnCaptures) 153 return false; 154 155 // Check isSafeToPrune() here rather than in shouldExplore() to avoid 156 // an expensive reachability query for every instruction we look at. 157 // Instead we only do one for actual capturing candidates. 158 if (isSafeToPrune(I)) 159 return false; 160 161 Captured = true; 162 return true; 163 } 164 165 const Instruction *BeforeHere; 166 const DominatorTree *DT; 167 168 bool ReturnCaptures; 169 bool IncludeI; 170 171 bool Captured; 172 }; 173 } 174 175 /// PointerMayBeCaptured - Return true if this pointer value may be captured 176 /// by the enclosing function (which is required to exist). This routine can 177 /// be expensive, so consider caching the results. The boolean ReturnCaptures 178 /// specifies whether returning the value (or part of it) from the function 179 /// counts as capturing it or not. The boolean StoreCaptures specified whether 180 /// storing the value (or part of it) into memory anywhere automatically 181 /// counts as capturing it or not. 182 bool llvm::PointerMayBeCaptured(const Value *V, 183 bool ReturnCaptures, bool StoreCaptures, 184 unsigned MaxUsesToExplore) { 185 assert(!isa<GlobalValue>(V) && 186 "It doesn't make sense to ask whether a global is captured."); 187 188 // TODO: If StoreCaptures is not true, we could do Fancy analysis 189 // to determine whether this store is not actually an escape point. 190 // In that case, BasicAliasAnalysis should be updated as well to 191 // take advantage of this. 192 (void)StoreCaptures; 193 194 SimpleCaptureTracker SCT(ReturnCaptures); 195 PointerMayBeCaptured(V, &SCT, MaxUsesToExplore); 196 if (SCT.Captured) 197 ++NumCaptured; 198 else 199 ++NumNotCaptured; 200 return SCT.Captured; 201 } 202 203 /// PointerMayBeCapturedBefore - Return true if this pointer value may be 204 /// captured by the enclosing function (which is required to exist). If a 205 /// DominatorTree is provided, only captures which happen before the given 206 /// instruction are considered. This routine can be expensive, so consider 207 /// caching the results. The boolean ReturnCaptures specifies whether 208 /// returning the value (or part of it) from the function counts as capturing 209 /// it or not. The boolean StoreCaptures specified whether storing the value 210 /// (or part of it) into memory anywhere automatically counts as capturing it 211 /// or not. 212 bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, 213 bool StoreCaptures, const Instruction *I, 214 const DominatorTree *DT, bool IncludeI, 215 unsigned MaxUsesToExplore) { 216 assert(!isa<GlobalValue>(V) && 217 "It doesn't make sense to ask whether a global is captured."); 218 219 if (!DT) 220 return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures, 221 MaxUsesToExplore); 222 223 // TODO: See comment in PointerMayBeCaptured regarding what could be done 224 // with StoreCaptures. 225 226 CapturesBefore CB(ReturnCaptures, I, DT, IncludeI); 227 PointerMayBeCaptured(V, &CB, MaxUsesToExplore); 228 if (CB.Captured) 229 ++NumCapturedBefore; 230 else 231 ++NumNotCapturedBefore; 232 return CB.Captured; 233 } 234 235 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker, 236 unsigned MaxUsesToExplore) { 237 assert(V->getType()->isPointerTy() && "Capture is for pointers only!"); 238 if (MaxUsesToExplore == 0) 239 MaxUsesToExplore = DefaultMaxUsesToExplore; 240 241 SmallVector<const Use *, 20> Worklist; 242 Worklist.reserve(getDefaultMaxUsesToExploreForCaptureTracking()); 243 SmallSet<const Use *, 20> Visited; 244 245 auto AddUses = [&](const Value *V) { 246 unsigned Count = 0; 247 for (const Use &U : V->uses()) { 248 // If there are lots of uses, conservatively say that the value 249 // is captured to avoid taking too much compile time. 250 if (Count++ >= MaxUsesToExplore) { 251 Tracker->tooManyUses(); 252 return false; 253 } 254 if (!Visited.insert(&U).second) 255 continue; 256 if (!Tracker->shouldExplore(&U)) 257 continue; 258 Worklist.push_back(&U); 259 } 260 return true; 261 }; 262 if (!AddUses(V)) 263 return; 264 265 while (!Worklist.empty()) { 266 const Use *U = Worklist.pop_back_val(); 267 Instruction *I = cast<Instruction>(U->getUser()); 268 269 switch (I->getOpcode()) { 270 case Instruction::Call: 271 case Instruction::Invoke: { 272 auto *Call = cast<CallBase>(I); 273 // Not captured if the callee is readonly, doesn't return a copy through 274 // its return value and doesn't unwind (a readonly function can leak bits 275 // by throwing an exception or not depending on the input value). 276 if (Call->onlyReadsMemory() && Call->doesNotThrow() && 277 Call->getType()->isVoidTy()) 278 break; 279 280 // The pointer is not captured if returned pointer is not captured. 281 // NOTE: CaptureTracking users should not assume that only functions 282 // marked with nocapture do not capture. This means that places like 283 // getUnderlyingObject in ValueTracking or DecomposeGEPExpression 284 // in BasicAA also need to know about this property. 285 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call, 286 true)) { 287 if (!AddUses(Call)) 288 return; 289 break; 290 } 291 292 // Volatile operations effectively capture the memory location that they 293 // load and store to. 294 if (auto *MI = dyn_cast<MemIntrinsic>(Call)) 295 if (MI->isVolatile()) 296 if (Tracker->captured(U)) 297 return; 298 299 // Not captured if only passed via 'nocapture' arguments. Note that 300 // calling a function pointer does not in itself cause the pointer to 301 // be captured. This is a subtle point considering that (for example) 302 // the callee might return its own address. It is analogous to saying 303 // that loading a value from a pointer does not cause the pointer to be 304 // captured, even though the loaded value might be the pointer itself 305 // (think of self-referential objects). 306 if (Call->isDataOperand(U) && 307 !Call->doesNotCapture(Call->getDataOperandNo(U))) { 308 // The parameter is not marked 'nocapture' - captured. 309 if (Tracker->captured(U)) 310 return; 311 } 312 break; 313 } 314 case Instruction::Load: 315 // Volatile loads make the address observable. 316 if (cast<LoadInst>(I)->isVolatile()) 317 if (Tracker->captured(U)) 318 return; 319 break; 320 case Instruction::VAArg: 321 // "va-arg" from a pointer does not cause it to be captured. 322 break; 323 case Instruction::Store: 324 // Stored the pointer - conservatively assume it may be captured. 325 // Volatile stores make the address observable. 326 if (U->getOperandNo() == 0 || cast<StoreInst>(I)->isVolatile()) 327 if (Tracker->captured(U)) 328 return; 329 break; 330 case Instruction::AtomicRMW: { 331 // atomicrmw conceptually includes both a load and store from 332 // the same location. 333 // As with a store, the location being accessed is not captured, 334 // but the value being stored is. 335 // Volatile stores make the address observable. 336 auto *ARMWI = cast<AtomicRMWInst>(I); 337 if (U->getOperandNo() == 1 || ARMWI->isVolatile()) 338 if (Tracker->captured(U)) 339 return; 340 break; 341 } 342 case Instruction::AtomicCmpXchg: { 343 // cmpxchg conceptually includes both a load and store from 344 // the same location. 345 // As with a store, the location being accessed is not captured, 346 // but the value being stored is. 347 // Volatile stores make the address observable. 348 auto *ACXI = cast<AtomicCmpXchgInst>(I); 349 if (U->getOperandNo() == 1 || U->getOperandNo() == 2 || 350 ACXI->isVolatile()) 351 if (Tracker->captured(U)) 352 return; 353 break; 354 } 355 case Instruction::BitCast: 356 case Instruction::GetElementPtr: 357 case Instruction::PHI: 358 case Instruction::Select: 359 case Instruction::AddrSpaceCast: 360 // The original value is not captured via this if the new value isn't. 361 if (!AddUses(I)) 362 return; 363 break; 364 case Instruction::ICmp: { 365 unsigned Idx = U->getOperandNo(); 366 unsigned OtherIdx = 1 - Idx; 367 if (auto *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(OtherIdx))) { 368 // Don't count comparisons of a no-alias return value against null as 369 // captures. This allows us to ignore comparisons of malloc results 370 // with null, for example. 371 if (CPN->getType()->getAddressSpace() == 0) 372 if (isNoAliasCall(U->get()->stripPointerCasts())) 373 break; 374 if (!I->getFunction()->nullPointerIsDefined()) { 375 auto *O = I->getOperand(Idx)->stripPointerCastsSameRepresentation(); 376 // Comparing a dereferenceable_or_null pointer against null cannot 377 // lead to pointer escapes, because if it is not null it must be a 378 // valid (in-bounds) pointer. 379 if (Tracker->isDereferenceableOrNull(O, I->getModule()->getDataLayout())) 380 break; 381 } 382 } 383 // Comparison against value stored in global variable. Given the pointer 384 // does not escape, its value cannot be guessed and stored separately in a 385 // global variable. 386 auto *LI = dyn_cast<LoadInst>(I->getOperand(OtherIdx)); 387 if (LI && isa<GlobalVariable>(LI->getPointerOperand())) 388 break; 389 // Otherwise, be conservative. There are crazy ways to capture pointers 390 // using comparisons. 391 if (Tracker->captured(U)) 392 return; 393 break; 394 } 395 default: 396 // Something else - be conservative and say it is captured. 397 if (Tracker->captured(U)) 398 return; 399 break; 400 } 401 } 402 403 // All uses examined. 404 } 405 406 bool llvm::isNonEscapingLocalObject( 407 const Value *V, SmallDenseMap<const Value *, bool, 8> *IsCapturedCache) { 408 SmallDenseMap<const Value *, bool, 8>::iterator CacheIt; 409 if (IsCapturedCache) { 410 bool Inserted; 411 std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false}); 412 if (!Inserted) 413 // Found cached result, return it! 414 return CacheIt->second; 415 } 416 417 // If this is an identified function-local object, check to see if it escapes. 418 if (isIdentifiedFunctionLocal(V)) { 419 // Set StoreCaptures to True so that we can assume in our callers that the 420 // pointer is not the result of a load instruction. Currently 421 // PointerMayBeCaptured doesn't have any special analysis for the 422 // StoreCaptures=false case; if it did, our callers could be refined to be 423 // more precise. 424 auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true); 425 if (IsCapturedCache) 426 CacheIt->second = Ret; 427 return Ret; 428 } 429 430 return false; 431 } 432