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 assert(I != BeforeHere && "Should have been handled earlier"); 110 111 BasicBlock *BB = I->getParent(); 112 // We explore this usage only if the usage can reach "BeforeHere". 113 // If use is not reachable from entry, there is no need to explore. 114 if (!DT->isReachableFromEntry(BB)) 115 return true; 116 117 // Compute the case where both instructions are inside the same basic 118 // block. 119 if (BB == BeforeHere->getParent()) { 120 // 'I' dominates 'BeforeHere' => not safe to prune. 121 // 122 // The value defined by an invoke dominates an instruction only 123 // if it dominates every instruction in UseBB. A PHI is dominated only 124 // if the instruction dominates every possible use in the UseBB. Since 125 // UseBB == BB, avoid pruning. 126 if (isa<InvokeInst>(BeforeHere) || isa<PHINode>(I)) 127 return false; 128 if (!BeforeHere->comesBefore(I)) 129 return false; 130 131 // 'BeforeHere' comes before 'I', it's safe to prune if we also 132 // guarantee that 'I' never reaches 'BeforeHere' through a back-edge or 133 // by its successors, i.e, prune if: 134 // 135 // (1) BB is an entry block or have no successors. 136 // (2) There's no path coming back through BB successors. 137 if (BB == &BB->getParent()->getEntryBlock() || 138 !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 // If the value is defined in the same basic block as use and BeforeHere, 147 // there is no need to explore the use if BeforeHere dominates use. 148 // Check whether there is a path from I to BeforeHere. 149 if (DT->dominates(BeforeHere, I) && 150 !isPotentiallyReachable(I, BeforeHere, nullptr, DT)) 151 return true; 152 153 return false; 154 } 155 156 bool shouldExplore(const Use *U) override { 157 Instruction *I = cast<Instruction>(U->getUser()); 158 159 if (BeforeHere == I) 160 return IncludeI; 161 162 return !isSafeToPrune(I); 163 } 164 165 bool captured(const Use *U) override { 166 if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures) 167 return false; 168 169 Captured = true; 170 return true; 171 } 172 173 const Instruction *BeforeHere; 174 const DominatorTree *DT; 175 176 bool ReturnCaptures; 177 bool IncludeI; 178 179 bool Captured; 180 }; 181 } 182 183 /// PointerMayBeCaptured - Return true if this pointer value may be captured 184 /// by the enclosing function (which is required to exist). This routine can 185 /// be expensive, so consider caching the results. The boolean ReturnCaptures 186 /// specifies whether returning the value (or part of it) from the function 187 /// counts as capturing it or not. The boolean StoreCaptures specified whether 188 /// storing the value (or part of it) into memory anywhere automatically 189 /// counts as capturing it or not. 190 bool llvm::PointerMayBeCaptured(const Value *V, 191 bool ReturnCaptures, bool StoreCaptures, 192 unsigned MaxUsesToExplore) { 193 assert(!isa<GlobalValue>(V) && 194 "It doesn't make sense to ask whether a global is captured."); 195 196 // TODO: If StoreCaptures is not true, we could do Fancy analysis 197 // to determine whether this store is not actually an escape point. 198 // In that case, BasicAliasAnalysis should be updated as well to 199 // take advantage of this. 200 (void)StoreCaptures; 201 202 SimpleCaptureTracker SCT(ReturnCaptures); 203 PointerMayBeCaptured(V, &SCT, MaxUsesToExplore); 204 if (SCT.Captured) 205 ++NumCaptured; 206 else 207 ++NumNotCaptured; 208 return SCT.Captured; 209 } 210 211 /// PointerMayBeCapturedBefore - Return true if this pointer value may be 212 /// captured by the enclosing function (which is required to exist). If a 213 /// DominatorTree is provided, only captures which happen before the given 214 /// instruction are considered. This routine can be expensive, so consider 215 /// caching the results. The boolean ReturnCaptures specifies whether 216 /// returning the value (or part of it) from the function counts as capturing 217 /// it or not. The boolean StoreCaptures specified whether storing the value 218 /// (or part of it) into memory anywhere automatically counts as capturing it 219 /// or not. 220 bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures, 221 bool StoreCaptures, const Instruction *I, 222 const DominatorTree *DT, bool IncludeI, 223 unsigned MaxUsesToExplore) { 224 assert(!isa<GlobalValue>(V) && 225 "It doesn't make sense to ask whether a global is captured."); 226 227 if (!DT) 228 return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures, 229 MaxUsesToExplore); 230 231 // TODO: See comment in PointerMayBeCaptured regarding what could be done 232 // with StoreCaptures. 233 234 CapturesBefore CB(ReturnCaptures, I, DT, IncludeI); 235 PointerMayBeCaptured(V, &CB, MaxUsesToExplore); 236 if (CB.Captured) 237 ++NumCapturedBefore; 238 else 239 ++NumNotCapturedBefore; 240 return CB.Captured; 241 } 242 243 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker, 244 unsigned MaxUsesToExplore) { 245 assert(V->getType()->isPointerTy() && "Capture is for pointers only!"); 246 if (MaxUsesToExplore == 0) 247 MaxUsesToExplore = DefaultMaxUsesToExplore; 248 249 SmallVector<const Use *, 20> Worklist; 250 Worklist.reserve(getDefaultMaxUsesToExploreForCaptureTracking()); 251 SmallSet<const Use *, 20> Visited; 252 253 auto AddUses = [&](const Value *V) { 254 unsigned Count = 0; 255 for (const Use &U : V->uses()) { 256 // If there are lots of uses, conservatively say that the value 257 // is captured to avoid taking too much compile time. 258 if (Count++ >= MaxUsesToExplore) { 259 Tracker->tooManyUses(); 260 return false; 261 } 262 if (!Visited.insert(&U).second) 263 continue; 264 if (!Tracker->shouldExplore(&U)) 265 continue; 266 Worklist.push_back(&U); 267 } 268 return true; 269 }; 270 if (!AddUses(V)) 271 return; 272 273 while (!Worklist.empty()) { 274 const Use *U = Worklist.pop_back_val(); 275 Instruction *I = cast<Instruction>(U->getUser()); 276 277 switch (I->getOpcode()) { 278 case Instruction::Call: 279 case Instruction::Invoke: { 280 auto *Call = cast<CallBase>(I); 281 // Not captured if the callee is readonly, doesn't return a copy through 282 // its return value and doesn't unwind (a readonly function can leak bits 283 // by throwing an exception or not depending on the input value). 284 if (Call->onlyReadsMemory() && Call->doesNotThrow() && 285 Call->getType()->isVoidTy()) 286 break; 287 288 // The pointer is not captured if returned pointer is not captured. 289 // NOTE: CaptureTracking users should not assume that only functions 290 // marked with nocapture do not capture. This means that places like 291 // getUnderlyingObject in ValueTracking or DecomposeGEPExpression 292 // in BasicAA also need to know about this property. 293 if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call, 294 true)) { 295 if (!AddUses(Call)) 296 return; 297 break; 298 } 299 300 // Volatile operations effectively capture the memory location that they 301 // load and store to. 302 if (auto *MI = dyn_cast<MemIntrinsic>(Call)) 303 if (MI->isVolatile()) 304 if (Tracker->captured(U)) 305 return; 306 307 // Not captured if only passed via 'nocapture' arguments. Note that 308 // calling a function pointer does not in itself cause the pointer to 309 // be captured. This is a subtle point considering that (for example) 310 // the callee might return its own address. It is analogous to saying 311 // that loading a value from a pointer does not cause the pointer to be 312 // captured, even though the loaded value might be the pointer itself 313 // (think of self-referential objects). 314 if (Call->isDataOperand(U) && 315 !Call->doesNotCapture(Call->getDataOperandNo(U))) { 316 // The parameter is not marked 'nocapture' - captured. 317 if (Tracker->captured(U)) 318 return; 319 } 320 break; 321 } 322 case Instruction::Load: 323 // Volatile loads make the address observable. 324 if (cast<LoadInst>(I)->isVolatile()) 325 if (Tracker->captured(U)) 326 return; 327 break; 328 case Instruction::VAArg: 329 // "va-arg" from a pointer does not cause it to be captured. 330 break; 331 case Instruction::Store: 332 // Stored the pointer - conservatively assume it may be captured. 333 // Volatile stores make the address observable. 334 if (U->getOperandNo() == 0 || cast<StoreInst>(I)->isVolatile()) 335 if (Tracker->captured(U)) 336 return; 337 break; 338 case Instruction::AtomicRMW: { 339 // atomicrmw conceptually includes both a load and store from 340 // the same location. 341 // As with a store, the location being accessed is not captured, 342 // but the value being stored is. 343 // Volatile stores make the address observable. 344 auto *ARMWI = cast<AtomicRMWInst>(I); 345 if (U->getOperandNo() == 1 || ARMWI->isVolatile()) 346 if (Tracker->captured(U)) 347 return; 348 break; 349 } 350 case Instruction::AtomicCmpXchg: { 351 // cmpxchg conceptually includes both a load and store from 352 // the same location. 353 // As with a store, the location being accessed is not captured, 354 // but the value being stored is. 355 // Volatile stores make the address observable. 356 auto *ACXI = cast<AtomicCmpXchgInst>(I); 357 if (U->getOperandNo() == 1 || U->getOperandNo() == 2 || 358 ACXI->isVolatile()) 359 if (Tracker->captured(U)) 360 return; 361 break; 362 } 363 case Instruction::BitCast: 364 case Instruction::GetElementPtr: 365 case Instruction::PHI: 366 case Instruction::Select: 367 case Instruction::AddrSpaceCast: 368 // The original value is not captured via this if the new value isn't. 369 if (!AddUses(I)) 370 return; 371 break; 372 case Instruction::ICmp: { 373 unsigned Idx = U->getOperandNo(); 374 unsigned OtherIdx = 1 - Idx; 375 if (auto *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(OtherIdx))) { 376 // Don't count comparisons of a no-alias return value against null as 377 // captures. This allows us to ignore comparisons of malloc results 378 // with null, for example. 379 if (CPN->getType()->getAddressSpace() == 0) 380 if (isNoAliasCall(U->get()->stripPointerCasts())) 381 break; 382 if (!I->getFunction()->nullPointerIsDefined()) { 383 auto *O = I->getOperand(Idx)->stripPointerCastsSameRepresentation(); 384 // Comparing a dereferenceable_or_null pointer against null cannot 385 // lead to pointer escapes, because if it is not null it must be a 386 // valid (in-bounds) pointer. 387 if (Tracker->isDereferenceableOrNull(O, I->getModule()->getDataLayout())) 388 break; 389 } 390 } 391 // Comparison against value stored in global variable. Given the pointer 392 // does not escape, its value cannot be guessed and stored separately in a 393 // global variable. 394 auto *LI = dyn_cast<LoadInst>(I->getOperand(OtherIdx)); 395 if (LI && isa<GlobalVariable>(LI->getPointerOperand())) 396 break; 397 // Otherwise, be conservative. There are crazy ways to capture pointers 398 // using comparisons. 399 if (Tracker->captured(U)) 400 return; 401 break; 402 } 403 default: 404 // Something else - be conservative and say it is captured. 405 if (Tracker->captured(U)) 406 return; 407 break; 408 } 409 } 410 411 // All uses examined. 412 } 413 414 bool llvm::isNonEscapingLocalObject( 415 const Value *V, SmallDenseMap<const Value *, bool, 8> *IsCapturedCache) { 416 SmallDenseMap<const Value *, bool, 8>::iterator CacheIt; 417 if (IsCapturedCache) { 418 bool Inserted; 419 std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false}); 420 if (!Inserted) 421 // Found cached result, return it! 422 return CacheIt->second; 423 } 424 425 // If this is an identified function-local object, check to see if it escapes. 426 if (isIdentifiedFunctionLocal(V)) { 427 // Set StoreCaptures to True so that we can assume in our callers that the 428 // pointer is not the result of a load instruction. Currently 429 // PointerMayBeCaptured doesn't have any special analysis for the 430 // StoreCaptures=false case; if it did, our callers could be refined to be 431 // more precise. 432 auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true); 433 if (IsCapturedCache) 434 CacheIt->second = Ret; 435 return Ret; 436 } 437 438 return false; 439 } 440