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