LLVM API Documentation

CaptureTracking.cpp
Go to the documentation of this file.
00001 //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
00002 //
00003 //                     The LLVM Compiler Infrastructure
00004 //
00005 // This file is distributed under the University of Illinois Open Source
00006 // License. See LICENSE.TXT for details.
00007 //
00008 //===----------------------------------------------------------------------===//
00009 //
00010 // This file contains routines that help determine which pointers are captured.
00011 // A pointer value is captured if the function makes a copy of any part of the
00012 // pointer that outlives the call.  Not being captured means, more or less, that
00013 // the pointer is only dereferenced and not stored in a global.  Returning part
00014 // of the pointer as the function return value may or may not count as capturing
00015 // the pointer, depending on the context.
00016 //
00017 //===----------------------------------------------------------------------===//
00018 
00019 #include "llvm/ADT/SmallSet.h"
00020 #include "llvm/ADT/SmallVector.h"
00021 #include "llvm/Analysis/AliasAnalysis.h"
00022 #include "llvm/Analysis/CaptureTracking.h"
00023 #include "llvm/IR/CallSite.h"
00024 #include "llvm/IR/Constants.h"
00025 #include "llvm/IR/Instructions.h"
00026 
00027 using namespace llvm;
00028 
00029 CaptureTracker::~CaptureTracker() {}
00030 
00031 bool CaptureTracker::shouldExplore(const Use *U) { return true; }
00032 
00033 namespace {
00034   struct SimpleCaptureTracker : public CaptureTracker {
00035     explicit SimpleCaptureTracker(bool ReturnCaptures)
00036       : ReturnCaptures(ReturnCaptures), Captured(false) {}
00037 
00038     void tooManyUses() override { Captured = true; }
00039 
00040     bool captured(const Use *U) override {
00041       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
00042         return false;
00043 
00044       Captured = true;
00045       return true;
00046     }
00047 
00048     bool ReturnCaptures;
00049 
00050     bool Captured;
00051   };
00052 }
00053 
00054 /// PointerMayBeCaptured - Return true if this pointer value may be captured
00055 /// by the enclosing function (which is required to exist).  This routine can
00056 /// be expensive, so consider caching the results.  The boolean ReturnCaptures
00057 /// specifies whether returning the value (or part of it) from the function
00058 /// counts as capturing it or not.  The boolean StoreCaptures specified whether
00059 /// storing the value (or part of it) into memory anywhere automatically
00060 /// counts as capturing it or not.
00061 bool llvm::PointerMayBeCaptured(const Value *V,
00062                                 bool ReturnCaptures, bool StoreCaptures) {
00063   assert(!isa<GlobalValue>(V) &&
00064          "It doesn't make sense to ask whether a global is captured.");
00065 
00066   // TODO: If StoreCaptures is not true, we could do Fancy analysis
00067   // to determine whether this store is not actually an escape point.
00068   // In that case, BasicAliasAnalysis should be updated as well to
00069   // take advantage of this.
00070   (void)StoreCaptures;
00071 
00072   SimpleCaptureTracker SCT(ReturnCaptures);
00073   PointerMayBeCaptured(V, &SCT);
00074   return SCT.Captured;
00075 }
00076 
00077 /// TODO: Write a new FunctionPass AliasAnalysis so that it can keep
00078 /// a cache. Then we can move the code from BasicAliasAnalysis into
00079 /// that path, and remove this threshold.
00080 static int const Threshold = 20;
00081 
00082 void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker) {
00083   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
00084   SmallVector<const Use *, Threshold> Worklist;
00085   SmallSet<const Use *, Threshold> Visited;
00086   int Count = 0;
00087 
00088   for (const Use &U : V->uses()) {
00089     // If there are lots of uses, conservatively say that the value
00090     // is captured to avoid taking too much compile time.
00091     if (Count++ >= Threshold)
00092       return Tracker->tooManyUses();
00093 
00094     if (!Tracker->shouldExplore(&U)) continue;
00095     Visited.insert(&U);
00096     Worklist.push_back(&U);
00097   }
00098 
00099   while (!Worklist.empty()) {
00100     const Use *U = Worklist.pop_back_val();
00101     Instruction *I = cast<Instruction>(U->getUser());
00102     V = U->get();
00103 
00104     switch (I->getOpcode()) {
00105     case Instruction::Call:
00106     case Instruction::Invoke: {
00107       CallSite CS(I);
00108       // Not captured if the callee is readonly, doesn't return a copy through
00109       // its return value and doesn't unwind (a readonly function can leak bits
00110       // by throwing an exception or not depending on the input value).
00111       if (CS.onlyReadsMemory() && CS.doesNotThrow() && I->getType()->isVoidTy())
00112         break;
00113 
00114       // Not captured if only passed via 'nocapture' arguments.  Note that
00115       // calling a function pointer does not in itself cause the pointer to
00116       // be captured.  This is a subtle point considering that (for example)
00117       // the callee might return its own address.  It is analogous to saying
00118       // that loading a value from a pointer does not cause the pointer to be
00119       // captured, even though the loaded value might be the pointer itself
00120       // (think of self-referential objects).
00121       CallSite::arg_iterator B = CS.arg_begin(), E = CS.arg_end();
00122       for (CallSite::arg_iterator A = B; A != E; ++A)
00123         if (A->get() == V && !CS.doesNotCapture(A - B))
00124           // The parameter is not marked 'nocapture' - captured.
00125           if (Tracker->captured(U))
00126             return;
00127       break;
00128     }
00129     case Instruction::Load:
00130       // Loading from a pointer does not cause it to be captured.
00131       break;
00132     case Instruction::VAArg:
00133       // "va-arg" from a pointer does not cause it to be captured.
00134       break;
00135     case Instruction::Store:
00136       if (V == I->getOperand(0))
00137         // Stored the pointer - conservatively assume it may be captured.
00138         if (Tracker->captured(U))
00139           return;
00140       // Storing to the pointee does not cause the pointer to be captured.
00141       break;
00142     case Instruction::BitCast:
00143     case Instruction::GetElementPtr:
00144     case Instruction::PHI:
00145     case Instruction::Select:
00146     case Instruction::AddrSpaceCast:
00147       // The original value is not captured via this if the new value isn't.
00148       Count = 0;
00149       for (Use &UU : I->uses()) {
00150         // If there are lots of uses, conservatively say that the value
00151         // is captured to avoid taking too much compile time.
00152         if (Count++ >= Threshold)
00153           return Tracker->tooManyUses();
00154 
00155         if (Visited.insert(&UU))
00156           if (Tracker->shouldExplore(&UU))
00157             Worklist.push_back(&UU);
00158       }
00159       break;
00160     case Instruction::ICmp:
00161       // Don't count comparisons of a no-alias return value against null as
00162       // captures. This allows us to ignore comparisons of malloc results
00163       // with null, for example.
00164       if (ConstantPointerNull *CPN =
00165           dyn_cast<ConstantPointerNull>(I->getOperand(1)))
00166         if (CPN->getType()->getAddressSpace() == 0)
00167           if (isNoAliasCall(V->stripPointerCasts()))
00168             break;
00169       // Otherwise, be conservative. There are crazy ways to capture pointers
00170       // using comparisons.
00171       if (Tracker->captured(U))
00172         return;
00173       break;
00174     default:
00175       // Something else - be conservative and say it is captured.
00176       if (Tracker->captured(U))
00177         return;
00178       break;
00179     }
00180   }
00181 
00182   // All uses examined.
00183 }