1e0aa0d67SDuncan Sands //===--- CaptureTracking.cpp - Determine whether a pointer is captured ----===//
2e0aa0d67SDuncan Sands //
32946cd70SChandler Carruth // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
42946cd70SChandler Carruth // See https://llvm.org/LICENSE.txt for license information.
52946cd70SChandler Carruth // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6e0aa0d67SDuncan Sands //
7e0aa0d67SDuncan Sands //===----------------------------------------------------------------------===//
8e0aa0d67SDuncan Sands //
9e0aa0d67SDuncan Sands // This file contains routines that help determine which pointers are captured.
10e0aa0d67SDuncan Sands // A pointer value is captured if the function makes a copy of any part of the
11e0aa0d67SDuncan Sands // pointer that outlives the call.  Not being captured means, more or less, that
12e0aa0d67SDuncan Sands // the pointer is only dereferenced and not stored in a global.  Returning part
13e0aa0d67SDuncan Sands // of the pointer as the function return value may or may not count as capturing
14e0aa0d67SDuncan Sands // the pointer, depending on the context.
15e0aa0d67SDuncan Sands //
16e0aa0d67SDuncan Sands //===----------------------------------------------------------------------===//
17e0aa0d67SDuncan Sands 
186bda14b3SChandler Carruth #include "llvm/Analysis/CaptureTracking.h"
1917fdacccSArthur Eubanks #include "llvm/ADT/SmallPtrSet.h"
20173bce3dSJakub Staszak #include "llvm/ADT/SmallSet.h"
21173bce3dSJakub Staszak #include "llvm/ADT/SmallVector.h"
2257b3bc8cSNikita Popov #include "llvm/ADT/Statistic.h"
23c733bf26SJakub Staszak #include "llvm/Analysis/AliasAnalysis.h"
24b0356217SHal Finkel #include "llvm/Analysis/CFG.h"
25d6f7346aSPiotr Padlewski #include "llvm/Analysis/ValueTracking.h"
26c733bf26SJakub Staszak #include "llvm/IR/Constants.h"
27b0356217SHal Finkel #include "llvm/IR/Dominators.h"
28c733bf26SJakub Staszak #include "llvm/IR/Instructions.h"
297f32420eSDavid Majnemer #include "llvm/IR/IntrinsicInst.h"
30cdceef4aSSimon Pilgrim #include "llvm/Support/CommandLine.h"
31c733bf26SJakub Staszak 
32e0aa0d67SDuncan Sands using namespace llvm;
33e0aa0d67SDuncan Sands 
3457b3bc8cSNikita Popov #define DEBUG_TYPE "capture-tracking"
3557b3bc8cSNikita Popov 
3657b3bc8cSNikita Popov STATISTIC(NumCaptured,          "Number of pointers maybe captured");
3757b3bc8cSNikita Popov STATISTIC(NumNotCaptured,       "Number of pointers not captured");
3857b3bc8cSNikita Popov STATISTIC(NumCapturedBefore,    "Number of pointers maybe captured before");
3957b3bc8cSNikita Popov STATISTIC(NumNotCapturedBefore, "Number of pointers not captured before");
4057b3bc8cSNikita Popov 
41c0d2bbb1SSerguei Katkov /// The default value for MaxUsesToExplore argument. It's relatively small to
42c0d2bbb1SSerguei Katkov /// keep the cost of analysis reasonable for clients like BasicAliasAnalysis,
43c0d2bbb1SSerguei Katkov /// where the results can't be cached.
44c0d2bbb1SSerguei Katkov /// TODO: we should probably introduce a caching CaptureTracking analysis and
45c0d2bbb1SSerguei Katkov /// use it where possible. The caching version can use much higher limit or
46c0d2bbb1SSerguei Katkov /// don't have this cap at all.
47c0d2bbb1SSerguei Katkov static cl::opt<unsigned>
48c0d2bbb1SSerguei Katkov     DefaultMaxUsesToExplore("capture-tracking-max-uses-to-explore", cl::Hidden,
49c0d2bbb1SSerguei Katkov                             cl::desc("Maximal number of uses to explore."),
50*78c6b148SFlorian Hahn                             cl::init(100));
51c0d2bbb1SSerguei Katkov 
getDefaultMaxUsesToExploreForCaptureTracking()52c0d2bbb1SSerguei Katkov unsigned llvm::getDefaultMaxUsesToExploreForCaptureTracking() {
53c0d2bbb1SSerguei Katkov   return DefaultMaxUsesToExplore;
54c0d2bbb1SSerguei Katkov }
55c0d2bbb1SSerguei Katkov 
563a3cb929SKazu Hirata CaptureTracker::~CaptureTracker() = default;
57aa2a00dbSNick Lewycky 
shouldExplore(const Use * U)5864e9aa5cSChandler Carruth bool CaptureTracker::shouldExplore(const Use *U) { return true; }
597c3b5d94SNick Lewycky 
isDereferenceableOrNull(Value * O,const DataLayout & DL)608b962f28SJohannes Doerfert bool CaptureTracker::isDereferenceableOrNull(Value *O, const DataLayout &DL) {
618b962f28SJohannes Doerfert   // An inbounds GEP can either be a valid pointer (pointing into
628b962f28SJohannes Doerfert   // or to the end of an allocation), or be null in the default
638b962f28SJohannes Doerfert   // address space. So for an inbounds GEP there is no way to let
648b962f28SJohannes Doerfert   // the pointer escape using clever GEP hacking because doing so
658b962f28SJohannes Doerfert   // would make the pointer point outside of the allocated object
668b962f28SJohannes Doerfert   // and thus make the GEP result a poison value. Similarly, other
678b962f28SJohannes Doerfert   // dereferenceable pointers cannot be manipulated without producing
688b962f28SJohannes Doerfert   // poison.
698b962f28SJohannes Doerfert   if (auto *GEP = dyn_cast<GetElementPtrInst>(O))
708b962f28SJohannes Doerfert     if (GEP->isInBounds())
718b962f28SJohannes Doerfert       return true;
725698537fSPhilip Reames   bool CanBeNull, CanBeFreed;
735698537fSPhilip Reames   return O->getPointerDereferenceableBytes(DL, CanBeNull, CanBeFreed);
748b962f28SJohannes Doerfert }
758b962f28SJohannes Doerfert 
767013a19eSNick Lewycky namespace {
776ae03c33SNick Lewycky   struct SimpleCaptureTracker : public CaptureTracker {
SimpleCaptureTracker__anonee76431a0111::SimpleCaptureTracker7817fdacccSArthur Eubanks     explicit SimpleCaptureTracker(
7917fdacccSArthur Eubanks 
8017fdacccSArthur Eubanks         const SmallPtrSetImpl<const Value *> &EphValues, bool ReturnCaptures)
8117fdacccSArthur Eubanks         : EphValues(EphValues), ReturnCaptures(ReturnCaptures) {}
827013a19eSNick Lewycky 
tooManyUses__anonee76431a0111::SimpleCaptureTracker83e9ba759cSCraig Topper     void tooManyUses() override { Captured = true; }
847013a19eSNick Lewycky 
captured__anonee76431a0111::SimpleCaptureTracker8564e9aa5cSChandler Carruth     bool captured(const Use *U) override {
864c378a44SNick Lewycky       if (isa<ReturnInst>(U->getUser()) && !ReturnCaptures)
877013a19eSNick Lewycky         return false;
887013a19eSNick Lewycky 
8917fdacccSArthur Eubanks       if (EphValues.contains(U->getUser()))
9017fdacccSArthur Eubanks         return false;
9117fdacccSArthur Eubanks 
927013a19eSNick Lewycky       Captured = true;
937013a19eSNick Lewycky       return true;
947013a19eSNick Lewycky     }
957013a19eSNick Lewycky 
9617fdacccSArthur Eubanks     const SmallPtrSetImpl<const Value *> &EphValues;
9717fdacccSArthur Eubanks 
987013a19eSNick Lewycky     bool ReturnCaptures;
997013a19eSNick Lewycky 
100b752eb88SKazu Hirata     bool Captured = false;
1017013a19eSNick Lewycky   };
102b0356217SHal Finkel 
103b0356217SHal Finkel   /// Only find pointer captures which happen before the given instruction. Uses
104b0356217SHal Finkel   /// the dominator tree to determine whether one instruction is before another.
105b0356217SHal Finkel   /// Only support the case where the Value is defined in the same basic block
106b0356217SHal Finkel   /// as the given instruction and the use.
107b0356217SHal Finkel   struct CapturesBefore : public CaptureTracker {
1087900ef89SBruno Cardoso Lopes 
CapturesBefore__anonee76431a0111::CapturesBefore1097f6a4826SFlorian Hahn     CapturesBefore(bool ReturnCaptures, const Instruction *I,
1107f6a4826SFlorian Hahn                    const DominatorTree *DT, bool IncludeI, const LoopInfo *LI)
1117f6a4826SFlorian Hahn         : BeforeHere(I), DT(DT), ReturnCaptures(ReturnCaptures),
112b752eb88SKazu Hirata           IncludeI(IncludeI), LI(LI) {}
113b0356217SHal Finkel 
tooManyUses__anonee76431a0111::CapturesBefore114b0356217SHal Finkel     void tooManyUses() override { Captured = true; }
115b0356217SHal Finkel 
isSafeToPrune__anonee76431a0111::CapturesBefore1167900ef89SBruno Cardoso Lopes     bool isSafeToPrune(Instruction *I) {
1176e9363c9SNikita Popov       if (BeforeHere == I)
1186e9363c9SNikita Popov         return !IncludeI;
119f765e54dSNikita Popov 
120b0356217SHal Finkel       // We explore this usage only if the usage can reach "BeforeHere".
121b0356217SHal Finkel       // If use is not reachable from entry, there is no need to explore.
12272431201SNikita Popov       if (!DT->isReachableFromEntry(I->getParent()))
1237900ef89SBruno Cardoso Lopes         return true;
1247900ef89SBruno Cardoso Lopes 
125afe92642SAnna Thomas       // Check whether there is a path from I to BeforeHere.
1267f6a4826SFlorian Hahn       return !isPotentiallyReachable(I, BeforeHere, nullptr, DT, LI);
1277900ef89SBruno Cardoso Lopes     }
1287900ef89SBruno Cardoso Lopes 
captured__anonee76431a0111::CapturesBefore129b0356217SHal Finkel     bool captured(const Use *U) override {
1306e9363c9SNikita Popov       Instruction *I = cast<Instruction>(U->getUser());
1316e9363c9SNikita Popov       if (isa<ReturnInst>(I) && !ReturnCaptures)
1326e9363c9SNikita Popov         return false;
1336e9363c9SNikita Popov 
1346e9363c9SNikita Popov       // Check isSafeToPrune() here rather than in shouldExplore() to avoid
1356e9363c9SNikita Popov       // an expensive reachability query for every instruction we look at.
1366e9363c9SNikita Popov       // Instead we only do one for actual capturing candidates.
1376e9363c9SNikita Popov       if (isSafeToPrune(I))
138b0356217SHal Finkel         return false;
139b0356217SHal Finkel 
140b0356217SHal Finkel       Captured = true;
141b0356217SHal Finkel       return true;
142b0356217SHal Finkel     }
143b0356217SHal Finkel 
144b0356217SHal Finkel     const Instruction *BeforeHere;
1453c148720SDaniel Neilson     const DominatorTree *DT;
146b0356217SHal Finkel 
147b0356217SHal Finkel     bool ReturnCaptures;
148d32803b6SHal Finkel     bool IncludeI;
149b0356217SHal Finkel 
150b752eb88SKazu Hirata     bool Captured = false;
1517f6a4826SFlorian Hahn 
1527f6a4826SFlorian Hahn     const LoopInfo *LI;
153b0356217SHal Finkel   };
1546f28fb70SFlorian Hahn 
1556f28fb70SFlorian Hahn   /// Find the 'earliest' instruction before which the pointer is known not to
1566f28fb70SFlorian Hahn   /// be captured. Here an instruction A is considered earlier than instruction
1576f28fb70SFlorian Hahn   /// B, if A dominates B. If 2 escapes do not dominate each other, the
1586f28fb70SFlorian Hahn   /// terminator of the common dominator is chosen. If not all uses cannot be
1596f28fb70SFlorian Hahn   /// analyzed, the earliest escape is set to the first instruction in the
1606f28fb70SFlorian Hahn   /// function entry block.
1616f28fb70SFlorian Hahn   // NOTE: Users have to make sure instructions compared against the earliest
1626f28fb70SFlorian Hahn   // escape are not in a cycle.
1636f28fb70SFlorian Hahn   struct EarliestCaptures : public CaptureTracker {
1646f28fb70SFlorian Hahn 
EarliestCaptures__anonee76431a0111::EarliestCaptures165b22ffc7bSArthur Eubanks     EarliestCaptures(bool ReturnCaptures, Function &F, const DominatorTree &DT,
166b22ffc7bSArthur Eubanks                      const SmallPtrSetImpl<const Value *> &EphValues)
167b22ffc7bSArthur Eubanks         : EphValues(EphValues), DT(DT), ReturnCaptures(ReturnCaptures), F(F) {}
1686f28fb70SFlorian Hahn 
tooManyUses__anonee76431a0111::EarliestCaptures1696f28fb70SFlorian Hahn     void tooManyUses() override {
1706f28fb70SFlorian Hahn       Captured = true;
1716f28fb70SFlorian Hahn       EarliestCapture = &*F.getEntryBlock().begin();
1726f28fb70SFlorian Hahn     }
1736f28fb70SFlorian Hahn 
captured__anonee76431a0111::EarliestCaptures1746f28fb70SFlorian Hahn     bool captured(const Use *U) override {
1756f28fb70SFlorian Hahn       Instruction *I = cast<Instruction>(U->getUser());
1766f28fb70SFlorian Hahn       if (isa<ReturnInst>(I) && !ReturnCaptures)
1776f28fb70SFlorian Hahn         return false;
1786f28fb70SFlorian Hahn 
179b22ffc7bSArthur Eubanks       if (EphValues.contains(I))
180b22ffc7bSArthur Eubanks         return false;
181b22ffc7bSArthur Eubanks 
1826f28fb70SFlorian Hahn       if (!EarliestCapture) {
1836f28fb70SFlorian Hahn         EarliestCapture = I;
1846f28fb70SFlorian Hahn       } else if (EarliestCapture->getParent() == I->getParent()) {
1856f28fb70SFlorian Hahn         if (I->comesBefore(EarliestCapture))
1866f28fb70SFlorian Hahn           EarliestCapture = I;
1876f28fb70SFlorian Hahn       } else {
1886f28fb70SFlorian Hahn         BasicBlock *CurrentBB = I->getParent();
1896f28fb70SFlorian Hahn         BasicBlock *EarliestBB = EarliestCapture->getParent();
1906f28fb70SFlorian Hahn         if (DT.dominates(EarliestBB, CurrentBB)) {
1916f28fb70SFlorian Hahn           // EarliestCapture already comes before the current use.
1926f28fb70SFlorian Hahn         } else if (DT.dominates(CurrentBB, EarliestBB)) {
1936f28fb70SFlorian Hahn           EarliestCapture = I;
1946f28fb70SFlorian Hahn         } else {
1956f28fb70SFlorian Hahn           // Otherwise find the nearest common dominator and use its terminator.
1966f28fb70SFlorian Hahn           auto *NearestCommonDom =
1976f28fb70SFlorian Hahn               DT.findNearestCommonDominator(CurrentBB, EarliestBB);
1986f28fb70SFlorian Hahn           EarliestCapture = NearestCommonDom->getTerminator();
1996f28fb70SFlorian Hahn         }
2006f28fb70SFlorian Hahn       }
2016f28fb70SFlorian Hahn       Captured = true;
2026f28fb70SFlorian Hahn 
2036f28fb70SFlorian Hahn       // Return false to continue analysis; we need to see all potential
2046f28fb70SFlorian Hahn       // captures.
2056f28fb70SFlorian Hahn       return false;
2066f28fb70SFlorian Hahn     }
2076f28fb70SFlorian Hahn 
208b22ffc7bSArthur Eubanks     const SmallPtrSetImpl<const Value *> &EphValues;
209b22ffc7bSArthur Eubanks 
2106f28fb70SFlorian Hahn     Instruction *EarliestCapture = nullptr;
2116f28fb70SFlorian Hahn 
2126f28fb70SFlorian Hahn     const DominatorTree &DT;
2136f28fb70SFlorian Hahn 
2146f28fb70SFlorian Hahn     bool ReturnCaptures;
2156f28fb70SFlorian Hahn 
216b752eb88SKazu Hirata     bool Captured = false;
2176f28fb70SFlorian Hahn 
2186f28fb70SFlorian Hahn     Function &F;
2196f28fb70SFlorian Hahn   };
220f00654e3SAlexander Kornienko }
2212d27b191SDan Gohman 
222e0aa0d67SDuncan Sands /// PointerMayBeCaptured - Return true if this pointer value may be captured
223e0aa0d67SDuncan Sands /// by the enclosing function (which is required to exist).  This routine can
224e0aa0d67SDuncan Sands /// be expensive, so consider caching the results.  The boolean ReturnCaptures
225e0aa0d67SDuncan Sands /// specifies whether returning the value (or part of it) from the function
22694e61762SDan Gohman /// counts as capturing it or not.  The boolean StoreCaptures specified whether
22794e61762SDan Gohman /// storing the value (or part of it) into memory anywhere automatically
228e0aa0d67SDuncan Sands /// counts as capturing it or not.
PointerMayBeCaptured(const Value * V,bool ReturnCaptures,bool StoreCaptures,unsigned MaxUsesToExplore)22917fdacccSArthur Eubanks bool llvm::PointerMayBeCaptured(const Value *V, bool ReturnCaptures,
23017fdacccSArthur Eubanks                                 bool StoreCaptures, unsigned MaxUsesToExplore) {
23117fdacccSArthur Eubanks   SmallPtrSet<const Value *, 1> Empty;
23217fdacccSArthur Eubanks   return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures, Empty,
23317fdacccSArthur Eubanks                               MaxUsesToExplore);
23417fdacccSArthur Eubanks }
23517fdacccSArthur Eubanks 
23617fdacccSArthur Eubanks /// Variant of the above function which accepts a set of Values that are
23717fdacccSArthur Eubanks /// ephemeral and cannot cause pointers to escape.
PointerMayBeCaptured(const Value * V,bool ReturnCaptures,bool StoreCaptures,const SmallPtrSetImpl<const Value * > & EphValues,unsigned MaxUsesToExplore)23817fdacccSArthur Eubanks bool llvm::PointerMayBeCaptured(const Value *V, bool ReturnCaptures,
23917fdacccSArthur Eubanks                                 bool StoreCaptures,
24017fdacccSArthur Eubanks                                 const SmallPtrSetImpl<const Value *> &EphValues,
241eba2365fSArtur Pilipenko                                 unsigned MaxUsesToExplore) {
242063ae589SNick Lewycky   assert(!isa<GlobalValue>(V) &&
243063ae589SNick Lewycky          "It doesn't make sense to ask whether a global is captured.");
244063ae589SNick Lewycky 
24594e61762SDan Gohman   // TODO: If StoreCaptures is not true, we could do Fancy analysis
24694e61762SDan Gohman   // to determine whether this store is not actually an escape point.
24794e61762SDan Gohman   // In that case, BasicAliasAnalysis should be updated as well to
24894e61762SDan Gohman   // take advantage of this.
2497013a19eSNick Lewycky   (void)StoreCaptures;
250e0aa0d67SDuncan Sands 
25117fdacccSArthur Eubanks   SimpleCaptureTracker SCT(EphValues, ReturnCaptures);
2522a0146e0SArtur Pilipenko   PointerMayBeCaptured(V, &SCT, MaxUsesToExplore);
25357b3bc8cSNikita Popov   if (SCT.Captured)
25457b3bc8cSNikita Popov     ++NumCaptured;
25557b3bc8cSNikita Popov   else
25657b3bc8cSNikita Popov     ++NumNotCaptured;
2577013a19eSNick Lewycky   return SCT.Captured;
258e0aa0d67SDuncan Sands }
2596ae03c33SNick Lewycky 
260b0356217SHal Finkel /// PointerMayBeCapturedBefore - Return true if this pointer value may be
261b0356217SHal Finkel /// captured by the enclosing function (which is required to exist). If a
262b0356217SHal Finkel /// DominatorTree is provided, only captures which happen before the given
263b0356217SHal Finkel /// instruction are considered. This routine can be expensive, so consider
264b0356217SHal Finkel /// caching the results.  The boolean ReturnCaptures specifies whether
265b0356217SHal Finkel /// returning the value (or part of it) from the function counts as capturing
266b0356217SHal Finkel /// it or not.  The boolean StoreCaptures specified whether storing the value
267b0356217SHal Finkel /// (or part of it) into memory anywhere automatically counts as capturing it
2680c2b09a9SReid Kleckner /// or not.
PointerMayBeCapturedBefore(const Value * V,bool ReturnCaptures,bool StoreCaptures,const Instruction * I,const DominatorTree * DT,bool IncludeI,unsigned MaxUsesToExplore,const LoopInfo * LI)269b0356217SHal Finkel bool llvm::PointerMayBeCapturedBefore(const Value *V, bool ReturnCaptures,
270b0356217SHal Finkel                                       bool StoreCaptures, const Instruction *I,
2713c148720SDaniel Neilson                                       const DominatorTree *DT, bool IncludeI,
2727f6a4826SFlorian Hahn                                       unsigned MaxUsesToExplore,
2737f6a4826SFlorian Hahn                                       const LoopInfo *LI) {
274b0356217SHal Finkel   assert(!isa<GlobalValue>(V) &&
275b0356217SHal Finkel          "It doesn't make sense to ask whether a global is captured.");
276b0356217SHal Finkel 
277b0356217SHal Finkel   if (!DT)
2782a0146e0SArtur Pilipenko     return PointerMayBeCaptured(V, ReturnCaptures, StoreCaptures,
2792a0146e0SArtur Pilipenko                                 MaxUsesToExplore);
280b0356217SHal Finkel 
281b0356217SHal Finkel   // TODO: See comment in PointerMayBeCaptured regarding what could be done
282b0356217SHal Finkel   // with StoreCaptures.
283b0356217SHal Finkel 
2847f6a4826SFlorian Hahn   CapturesBefore CB(ReturnCaptures, I, DT, IncludeI, LI);
2852a0146e0SArtur Pilipenko   PointerMayBeCaptured(V, &CB, MaxUsesToExplore);
28657b3bc8cSNikita Popov   if (CB.Captured)
28757b3bc8cSNikita Popov     ++NumCapturedBefore;
28857b3bc8cSNikita Popov   else
28957b3bc8cSNikita Popov     ++NumNotCapturedBefore;
290b0356217SHal Finkel   return CB.Captured;
291b0356217SHal Finkel }
292b0356217SHal Finkel 
293b22ffc7bSArthur Eubanks Instruction *
FindEarliestCapture(const Value * V,Function & F,bool ReturnCaptures,bool StoreCaptures,const DominatorTree & DT,const SmallPtrSetImpl<const Value * > & EphValues,unsigned MaxUsesToExplore)294b22ffc7bSArthur Eubanks llvm::FindEarliestCapture(const Value *V, Function &F, bool ReturnCaptures,
295b22ffc7bSArthur Eubanks                           bool StoreCaptures, const DominatorTree &DT,
296b22ffc7bSArthur Eubanks 
297b22ffc7bSArthur Eubanks                           const SmallPtrSetImpl<const Value *> &EphValues,
2986f28fb70SFlorian Hahn                           unsigned MaxUsesToExplore) {
2996f28fb70SFlorian Hahn   assert(!isa<GlobalValue>(V) &&
3006f28fb70SFlorian Hahn          "It doesn't make sense to ask whether a global is captured.");
3016f28fb70SFlorian Hahn 
302b22ffc7bSArthur Eubanks   EarliestCaptures CB(ReturnCaptures, F, DT, EphValues);
3036f28fb70SFlorian Hahn   PointerMayBeCaptured(V, &CB, MaxUsesToExplore);
3046f28fb70SFlorian Hahn   if (CB.Captured)
3056f28fb70SFlorian Hahn     ++NumCapturedBefore;
3066f28fb70SFlorian Hahn   else
3076f28fb70SFlorian Hahn     ++NumNotCapturedBefore;
3086f28fb70SFlorian Hahn   return CB.EarliestCapture;
3096f28fb70SFlorian Hahn }
3106f28fb70SFlorian Hahn 
DetermineUseCaptureKind(const Use & U,function_ref<bool (Value *,const DataLayout &)> IsDereferenceableOrNull)311d6e09ce8SJohannes Doerfert UseCaptureKind llvm::DetermineUseCaptureKind(
312d6e09ce8SJohannes Doerfert     const Use &U,
313d6e09ce8SJohannes Doerfert     function_ref<bool(Value *, const DataLayout &)> IsDereferenceableOrNull) {
314d6e09ce8SJohannes Doerfert   Instruction *I = cast<Instruction>(U.getUser());
315d6e09ce8SJohannes Doerfert 
316d6e09ce8SJohannes Doerfert   switch (I->getOpcode()) {
317d6e09ce8SJohannes Doerfert   case Instruction::Call:
318d6e09ce8SJohannes Doerfert   case Instruction::Invoke: {
319d6e09ce8SJohannes Doerfert     auto *Call = cast<CallBase>(I);
320d6e09ce8SJohannes Doerfert     // Not captured if the callee is readonly, doesn't return a copy through
321d6e09ce8SJohannes Doerfert     // its return value and doesn't unwind (a readonly function can leak bits
322d6e09ce8SJohannes Doerfert     // by throwing an exception or not depending on the input value).
323d6e09ce8SJohannes Doerfert     if (Call->onlyReadsMemory() && Call->doesNotThrow() &&
324d6e09ce8SJohannes Doerfert         Call->getType()->isVoidTy())
325d6e09ce8SJohannes Doerfert       return UseCaptureKind::NO_CAPTURE;
326d6e09ce8SJohannes Doerfert 
327d6e09ce8SJohannes Doerfert     // The pointer is not captured if returned pointer is not captured.
328d6e09ce8SJohannes Doerfert     // NOTE: CaptureTracking users should not assume that only functions
329d6e09ce8SJohannes Doerfert     // marked with nocapture do not capture. This means that places like
330d6e09ce8SJohannes Doerfert     // getUnderlyingObject in ValueTracking or DecomposeGEPExpression
331d6e09ce8SJohannes Doerfert     // in BasicAA also need to know about this property.
332d6e09ce8SJohannes Doerfert     if (isIntrinsicReturningPointerAliasingArgumentWithoutCapturing(Call, true))
333d6e09ce8SJohannes Doerfert       return UseCaptureKind::PASSTHROUGH;
334d6e09ce8SJohannes Doerfert 
335d6e09ce8SJohannes Doerfert     // Volatile operations effectively capture the memory location that they
336d6e09ce8SJohannes Doerfert     // load and store to.
337d6e09ce8SJohannes Doerfert     if (auto *MI = dyn_cast<MemIntrinsic>(Call))
338d6e09ce8SJohannes Doerfert       if (MI->isVolatile())
339d6e09ce8SJohannes Doerfert         return UseCaptureKind::MAY_CAPTURE;
340d6e09ce8SJohannes Doerfert 
341d6e09ce8SJohannes Doerfert     // Calling a function pointer does not in itself cause the pointer to
342d6e09ce8SJohannes Doerfert     // be captured.  This is a subtle point considering that (for example)
343d6e09ce8SJohannes Doerfert     // the callee might return its own address.  It is analogous to saying
344d6e09ce8SJohannes Doerfert     // that loading a value from a pointer does not cause the pointer to be
345d6e09ce8SJohannes Doerfert     // captured, even though the loaded value might be the pointer itself
346d6e09ce8SJohannes Doerfert     // (think of self-referential objects).
347d6e09ce8SJohannes Doerfert     if (Call->isCallee(&U))
348d6e09ce8SJohannes Doerfert       return UseCaptureKind::NO_CAPTURE;
349d6e09ce8SJohannes Doerfert 
350d6e09ce8SJohannes Doerfert     // Not captured if only passed via 'nocapture' arguments.
351d6e09ce8SJohannes Doerfert     if (Call->isDataOperand(&U) &&
352d6e09ce8SJohannes Doerfert         !Call->doesNotCapture(Call->getDataOperandNo(&U))) {
353d6e09ce8SJohannes Doerfert       // The parameter is not marked 'nocapture' - captured.
354d6e09ce8SJohannes Doerfert       return UseCaptureKind::MAY_CAPTURE;
355d6e09ce8SJohannes Doerfert     }
356d6e09ce8SJohannes Doerfert     return UseCaptureKind::NO_CAPTURE;
357d6e09ce8SJohannes Doerfert   }
358d6e09ce8SJohannes Doerfert   case Instruction::Load:
359d6e09ce8SJohannes Doerfert     // Volatile loads make the address observable.
360d6e09ce8SJohannes Doerfert     if (cast<LoadInst>(I)->isVolatile())
361d6e09ce8SJohannes Doerfert       return UseCaptureKind::MAY_CAPTURE;
362d6e09ce8SJohannes Doerfert     return UseCaptureKind::NO_CAPTURE;
363d6e09ce8SJohannes Doerfert   case Instruction::VAArg:
364d6e09ce8SJohannes Doerfert     // "va-arg" from a pointer does not cause it to be captured.
365d6e09ce8SJohannes Doerfert     return UseCaptureKind::NO_CAPTURE;
366d6e09ce8SJohannes Doerfert   case Instruction::Store:
367d6e09ce8SJohannes Doerfert     // Stored the pointer - conservatively assume it may be captured.
368d6e09ce8SJohannes Doerfert     // Volatile stores make the address observable.
369d6e09ce8SJohannes Doerfert     if (U.getOperandNo() == 0 || cast<StoreInst>(I)->isVolatile())
370d6e09ce8SJohannes Doerfert       return UseCaptureKind::MAY_CAPTURE;
371d6e09ce8SJohannes Doerfert     return UseCaptureKind::NO_CAPTURE;
372d6e09ce8SJohannes Doerfert   case Instruction::AtomicRMW: {
373d6e09ce8SJohannes Doerfert     // atomicrmw conceptually includes both a load and store from
374d6e09ce8SJohannes Doerfert     // the same location.
375d6e09ce8SJohannes Doerfert     // As with a store, the location being accessed is not captured,
376d6e09ce8SJohannes Doerfert     // but the value being stored is.
377d6e09ce8SJohannes Doerfert     // Volatile stores make the address observable.
378d6e09ce8SJohannes Doerfert     auto *ARMWI = cast<AtomicRMWInst>(I);
379d6e09ce8SJohannes Doerfert     if (U.getOperandNo() == 1 || ARMWI->isVolatile())
380d6e09ce8SJohannes Doerfert       return UseCaptureKind::MAY_CAPTURE;
381d6e09ce8SJohannes Doerfert     return UseCaptureKind::NO_CAPTURE;
382d6e09ce8SJohannes Doerfert   }
383d6e09ce8SJohannes Doerfert   case Instruction::AtomicCmpXchg: {
384d6e09ce8SJohannes Doerfert     // cmpxchg conceptually includes both a load and store from
385d6e09ce8SJohannes Doerfert     // the same location.
386d6e09ce8SJohannes Doerfert     // As with a store, the location being accessed is not captured,
387d6e09ce8SJohannes Doerfert     // but the value being stored is.
388d6e09ce8SJohannes Doerfert     // Volatile stores make the address observable.
389d6e09ce8SJohannes Doerfert     auto *ACXI = cast<AtomicCmpXchgInst>(I);
390d6e09ce8SJohannes Doerfert     if (U.getOperandNo() == 1 || U.getOperandNo() == 2 || ACXI->isVolatile())
391d6e09ce8SJohannes Doerfert       return UseCaptureKind::MAY_CAPTURE;
392d6e09ce8SJohannes Doerfert     return UseCaptureKind::NO_CAPTURE;
393d6e09ce8SJohannes Doerfert   }
394d6e09ce8SJohannes Doerfert   case Instruction::BitCast:
395d6e09ce8SJohannes Doerfert   case Instruction::GetElementPtr:
396d6e09ce8SJohannes Doerfert   case Instruction::PHI:
397d6e09ce8SJohannes Doerfert   case Instruction::Select:
398d6e09ce8SJohannes Doerfert   case Instruction::AddrSpaceCast:
399d6e09ce8SJohannes Doerfert     // The original value is not captured via this if the new value isn't.
400d6e09ce8SJohannes Doerfert     return UseCaptureKind::PASSTHROUGH;
401d6e09ce8SJohannes Doerfert   case Instruction::ICmp: {
402d6e09ce8SJohannes Doerfert     unsigned Idx = U.getOperandNo();
403d6e09ce8SJohannes Doerfert     unsigned OtherIdx = 1 - Idx;
404d6e09ce8SJohannes Doerfert     if (auto *CPN = dyn_cast<ConstantPointerNull>(I->getOperand(OtherIdx))) {
405d6e09ce8SJohannes Doerfert       // Don't count comparisons of a no-alias return value against null as
406d6e09ce8SJohannes Doerfert       // captures. This allows us to ignore comparisons of malloc results
407d6e09ce8SJohannes Doerfert       // with null, for example.
408d6e09ce8SJohannes Doerfert       if (CPN->getType()->getAddressSpace() == 0)
409d6e09ce8SJohannes Doerfert         if (isNoAliasCall(U.get()->stripPointerCasts()))
410d6e09ce8SJohannes Doerfert           return UseCaptureKind::NO_CAPTURE;
411d6e09ce8SJohannes Doerfert       if (!I->getFunction()->nullPointerIsDefined()) {
412d6e09ce8SJohannes Doerfert         auto *O = I->getOperand(Idx)->stripPointerCastsSameRepresentation();
413d6e09ce8SJohannes Doerfert         // Comparing a dereferenceable_or_null pointer against null cannot
414d6e09ce8SJohannes Doerfert         // lead to pointer escapes, because if it is not null it must be a
415d6e09ce8SJohannes Doerfert         // valid (in-bounds) pointer.
416d6e09ce8SJohannes Doerfert         const DataLayout &DL = I->getModule()->getDataLayout();
417d6e09ce8SJohannes Doerfert         if (IsDereferenceableOrNull && IsDereferenceableOrNull(O, DL))
418d6e09ce8SJohannes Doerfert           return UseCaptureKind::NO_CAPTURE;
419d6e09ce8SJohannes Doerfert       }
420d6e09ce8SJohannes Doerfert     }
421d6e09ce8SJohannes Doerfert     // Comparison against value stored in global variable. Given the pointer
422d6e09ce8SJohannes Doerfert     // does not escape, its value cannot be guessed and stored separately in a
423d6e09ce8SJohannes Doerfert     // global variable.
424d6e09ce8SJohannes Doerfert     auto *LI = dyn_cast<LoadInst>(I->getOperand(OtherIdx));
425d6e09ce8SJohannes Doerfert     if (LI && isa<GlobalVariable>(LI->getPointerOperand()))
426d6e09ce8SJohannes Doerfert       return UseCaptureKind::NO_CAPTURE;
427d6e09ce8SJohannes Doerfert     // Otherwise, be conservative. There are crazy ways to capture pointers
428d6e09ce8SJohannes Doerfert     // using comparisons.
429d6e09ce8SJohannes Doerfert     return UseCaptureKind::MAY_CAPTURE;
430d6e09ce8SJohannes Doerfert   }
431d6e09ce8SJohannes Doerfert   default:
432d6e09ce8SJohannes Doerfert     // Something else - be conservative and say it is captured.
433d6e09ce8SJohannes Doerfert     return UseCaptureKind::MAY_CAPTURE;
434d6e09ce8SJohannes Doerfert   }
435d6e09ce8SJohannes Doerfert }
436d6e09ce8SJohannes Doerfert 
PointerMayBeCaptured(const Value * V,CaptureTracker * Tracker,unsigned MaxUsesToExplore)437eba2365fSArtur Pilipenko void llvm::PointerMayBeCaptured(const Value *V, CaptureTracker *Tracker,
438eba2365fSArtur Pilipenko                                 unsigned MaxUsesToExplore) {
4396ae03c33SNick Lewycky   assert(V->getType()->isPointerTy() && "Capture is for pointers only!");
4402b282755SNikita Popov   if (MaxUsesToExplore == 0)
4412b282755SNikita Popov     MaxUsesToExplore = DefaultMaxUsesToExplore;
4422b282755SNikita Popov 
443c0d2bbb1SSerguei Katkov   SmallVector<const Use *, 20> Worklist;
444c0d2bbb1SSerguei Katkov   Worklist.reserve(getDefaultMaxUsesToExploreForCaptureTracking());
445c0d2bbb1SSerguei Katkov   SmallSet<const Use *, 20> Visited;
4466ae03c33SNick Lewycky 
447e9832dfdSPiotr Padlewski   auto AddUses = [&](const Value *V) {
448cdf47884SChandler Carruth     for (const Use &U : V->uses()) {
4496ae03c33SNick Lewycky       // If there are lots of uses, conservatively say that the value
4506ae03c33SNick Lewycky       // is captured to avoid taking too much compile time.
451*78c6b148SFlorian Hahn       if (Visited.size()  >= MaxUsesToExplore) {
452f63ab188SNikita Popov         Tracker->tooManyUses();
453f63ab188SNikita Popov         return false;
454f63ab188SNikita Popov       }
455e9832dfdSPiotr Padlewski       if (!Visited.insert(&U).second)
456e9832dfdSPiotr Padlewski         continue;
457e9832dfdSPiotr Padlewski       if (!Tracker->shouldExplore(&U))
458e9832dfdSPiotr Padlewski         continue;
459cdf47884SChandler Carruth       Worklist.push_back(&U);
4606ae03c33SNick Lewycky     }
461f63ab188SNikita Popov     return true;
462e9832dfdSPiotr Padlewski   };
463f63ab188SNikita Popov   if (!AddUses(V))
464f63ab188SNikita Popov     return;
4656ae03c33SNick Lewycky 
466d6e09ce8SJohannes Doerfert   auto IsDereferenceableOrNull = [Tracker](Value *V, const DataLayout &DL) {
467d6e09ce8SJohannes Doerfert     return Tracker->isDereferenceableOrNull(V, DL);
468d6e09ce8SJohannes Doerfert   };
4696ae03c33SNick Lewycky   while (!Worklist.empty()) {
47064e9aa5cSChandler Carruth     const Use *U = Worklist.pop_back_val();
471d6e09ce8SJohannes Doerfert     switch (DetermineUseCaptureKind(*U, IsDereferenceableOrNull)) {
472d6e09ce8SJohannes Doerfert     case UseCaptureKind::NO_CAPTURE:
473d6e09ce8SJohannes Doerfert       continue;
474d6e09ce8SJohannes Doerfert     case UseCaptureKind::MAY_CAPTURE:
4757f32420eSDavid Majnemer       if (Tracker->captured(U))
4767f32420eSDavid Majnemer         return;
477d6e09ce8SJohannes Doerfert       continue;
478d6e09ce8SJohannes Doerfert     case UseCaptureKind::PASSTHROUGH:
479d6e09ce8SJohannes Doerfert       if (!AddUses(U->getUser()))
4806ae03c33SNick Lewycky         return;
481d6e09ce8SJohannes Doerfert       continue;
4826ae03c33SNick Lewycky     }
4836ae03c33SNick Lewycky   }
4846ae03c33SNick Lewycky 
4856ae03c33SNick Lewycky   // All uses examined.
4866ae03c33SNick Lewycky }
487224fd6ffSAnh Tuyen Tran 
isNonEscapingLocalObject(const Value * V,SmallDenseMap<const Value *,bool,8> * IsCapturedCache)488224fd6ffSAnh Tuyen Tran bool llvm::isNonEscapingLocalObject(
489224fd6ffSAnh Tuyen Tran     const Value *V, SmallDenseMap<const Value *, bool, 8> *IsCapturedCache) {
490224fd6ffSAnh Tuyen Tran   SmallDenseMap<const Value *, bool, 8>::iterator CacheIt;
491224fd6ffSAnh Tuyen Tran   if (IsCapturedCache) {
492224fd6ffSAnh Tuyen Tran     bool Inserted;
493224fd6ffSAnh Tuyen Tran     std::tie(CacheIt, Inserted) = IsCapturedCache->insert({V, false});
494224fd6ffSAnh Tuyen Tran     if (!Inserted)
495224fd6ffSAnh Tuyen Tran       // Found cached result, return it!
496224fd6ffSAnh Tuyen Tran       return CacheIt->second;
497224fd6ffSAnh Tuyen Tran   }
498224fd6ffSAnh Tuyen Tran 
499425781bcSNikita Popov   // If this is an identified function-local object, check to see if it escapes.
500425781bcSNikita Popov   if (isIdentifiedFunctionLocal(V)) {
501224fd6ffSAnh Tuyen Tran     // Set StoreCaptures to True so that we can assume in our callers that the
502224fd6ffSAnh Tuyen Tran     // pointer is not the result of a load instruction. Currently
503224fd6ffSAnh Tuyen Tran     // PointerMayBeCaptured doesn't have any special analysis for the
504224fd6ffSAnh Tuyen Tran     // StoreCaptures=false case; if it did, our callers could be refined to be
505224fd6ffSAnh Tuyen Tran     // more precise.
506224fd6ffSAnh Tuyen Tran     auto Ret = !PointerMayBeCaptured(V, false, /*StoreCaptures=*/true);
507224fd6ffSAnh Tuyen Tran     if (IsCapturedCache)
508224fd6ffSAnh Tuyen Tran       CacheIt->second = Ret;
509224fd6ffSAnh Tuyen Tran     return Ret;
510224fd6ffSAnh Tuyen Tran   }
511224fd6ffSAnh Tuyen Tran 
512224fd6ffSAnh Tuyen Tran   return false;
513224fd6ffSAnh Tuyen Tran }
514