LLVM  8.0.1
ProvenanceAnalysis.cpp
Go to the documentation of this file.
1 //===- ProvenanceAnalysis.cpp - ObjC ARC Optimization ---------------------===//
2 //
3 // The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 /// \file
11 ///
12 /// This file defines a special form of Alias Analysis called ``Provenance
13 /// Analysis''. The word ``provenance'' refers to the history of the ownership
14 /// of an object. Thus ``Provenance Analysis'' is an analysis which attempts to
15 /// use various techniques to determine if locally
16 ///
17 /// WARNING: This file knows about certain library functions. It recognizes them
18 /// by name, and hardwires knowledge of their semantics.
19 ///
20 /// WARNING: This file knows about how certain Objective-C library functions are
21 /// used. Naive LLVM IR transformations which would otherwise be
22 /// behavior-preserving may break these assumptions.
23 //
24 //===----------------------------------------------------------------------===//
25 
26 #include "ProvenanceAnalysis.h"
27 #include "llvm/ADT/SmallPtrSet.h"
28 #include "llvm/ADT/SmallVector.h"
31 #include "llvm/IR/Instructions.h"
32 #include "llvm/IR/Module.h"
33 #include "llvm/IR/Use.h"
34 #include "llvm/IR/User.h"
35 #include "llvm/IR/Value.h"
36 #include "llvm/Support/Casting.h"
37 #include <utility>
38 
39 using namespace llvm;
40 using namespace llvm::objcarc;
41 
42 bool ProvenanceAnalysis::relatedSelect(const SelectInst *A,
43  const Value *B) {
44  const DataLayout &DL = A->getModule()->getDataLayout();
45  // If the values are Selects with the same condition, we can do a more precise
46  // check: just check for relations between the values on corresponding arms.
47  if (const SelectInst *SB = dyn_cast<SelectInst>(B))
48  if (A->getCondition() == SB->getCondition())
49  return related(A->getTrueValue(), SB->getTrueValue(), DL) ||
50  related(A->getFalseValue(), SB->getFalseValue(), DL);
51 
52  // Check both arms of the Select node individually.
53  return related(A->getTrueValue(), B, DL) ||
54  related(A->getFalseValue(), B, DL);
55 }
56 
57 bool ProvenanceAnalysis::relatedPHI(const PHINode *A,
58  const Value *B) {
59  const DataLayout &DL = A->getModule()->getDataLayout();
60  // If the values are PHIs in the same block, we can do a more precise as well
61  // as efficient check: just check for relations between the values on
62  // corresponding edges.
63  if (const PHINode *PNB = dyn_cast<PHINode>(B))
64  if (PNB->getParent() == A->getParent()) {
65  for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
66  if (related(A->getIncomingValue(i),
67  PNB->getIncomingValueForBlock(A->getIncomingBlock(i)), DL))
68  return true;
69  return false;
70  }
71 
72  // Check each unique source of the PHI node against B.
74  for (Value *PV1 : A->incoming_values()) {
75  if (UniqueSrc.insert(PV1).second && related(PV1, B, DL))
76  return true;
77  }
78 
79  // All of the arms checked out.
80  return false;
81 }
82 
83 /// Test if the value of P, or any value covered by its provenance, is ever
84 /// stored within the function (not counting callees).
85 static bool IsStoredObjCPointer(const Value *P) {
88  Worklist.push_back(P);
89  Visited.insert(P);
90  do {
91  P = Worklist.pop_back_val();
92  for (const Use &U : P->uses()) {
93  const User *Ur = U.getUser();
94  if (isa<StoreInst>(Ur)) {
95  if (U.getOperandNo() == 0)
96  // The pointer is stored.
97  return true;
98  // The pointed is stored through.
99  continue;
100  }
101  if (isa<CallInst>(Ur))
102  // The pointer is passed as an argument, ignore this.
103  continue;
104  if (isa<PtrToIntInst>(P))
105  // Assume the worst.
106  return true;
107  if (Visited.insert(Ur).second)
108  Worklist.push_back(Ur);
109  }
110  } while (!Worklist.empty());
111 
112  // Everything checked out.
113  return false;
114 }
115 
116 bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B,
117  const DataLayout &DL) {
118  // Ask regular AliasAnalysis, for a first approximation.
119  switch (AA->alias(A, B)) {
120  case NoAlias:
121  return false;
122  case MustAlias:
123  case PartialAlias:
124  return true;
125  case MayAlias:
126  break;
127  }
128 
129  bool AIsIdentified = IsObjCIdentifiedObject(A);
130  bool BIsIdentified = IsObjCIdentifiedObject(B);
131 
132  // An ObjC-Identified object can't alias a load if it is never locally stored.
133  if (AIsIdentified) {
134  // Check for an obvious escape.
135  if (isa<LoadInst>(B))
136  return IsStoredObjCPointer(A);
137  if (BIsIdentified) {
138  // Check for an obvious escape.
139  if (isa<LoadInst>(A))
140  return IsStoredObjCPointer(B);
141  // Both pointers are identified and escapes aren't an evident problem.
142  return false;
143  }
144  } else if (BIsIdentified) {
145  // Check for an obvious escape.
146  if (isa<LoadInst>(A))
147  return IsStoredObjCPointer(B);
148  }
149 
150  // Special handling for PHI and Select.
151  if (const PHINode *PN = dyn_cast<PHINode>(A))
152  return relatedPHI(PN, B);
153  if (const PHINode *PN = dyn_cast<PHINode>(B))
154  return relatedPHI(PN, A);
155  if (const SelectInst *S = dyn_cast<SelectInst>(A))
156  return relatedSelect(S, B);
157  if (const SelectInst *S = dyn_cast<SelectInst>(B))
158  return relatedSelect(S, A);
159 
160  // Conservative.
161  return true;
162 }
163 
164 bool ProvenanceAnalysis::related(const Value *A, const Value *B,
165  const DataLayout &DL) {
166  A = GetUnderlyingObjCPtrCached(A, DL, UnderlyingObjCPtrCache);
167  B = GetUnderlyingObjCPtrCached(B, DL, UnderlyingObjCPtrCache);
168 
169  // Quick check.
170  if (A == B)
171  return true;
172 
173  // Begin by inserting a conservative value into the map. If the insertion
174  // fails, we have the answer already. If it succeeds, leave it there until we
175  // compute the real answer to guard against recursive queries.
176  if (A > B) std::swap(A, B);
177  std::pair<CachedResultsTy::iterator, bool> Pair =
178  CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
179  if (!Pair.second)
180  return Pair.first->second;
181 
182  bool Result = relatedCheck(A, B, DL);
183  CachedResults[ValuePairTy(A, B)] = Result;
184  return Result;
185 }
A parsed version of the target data layout string in and methods for querying it. ...
Definition: DataLayout.h:111
iterator_range< use_iterator > uses()
Definition: Value.h:355
This class represents lattice values for constants.
Definition: AllocatorList.h:24
const Value * getTrueValue() const
The two locations do not alias at all.
Definition: AliasAnalysis.h:84
This defines the Use class.
bool IsObjCIdentifiedObject(const Value *V)
Return true if this value refers to a distinct and identifiable object.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Definition: DenseMap.h:221
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
This class represents the LLVM &#39;select&#39; instruction.
const DataLayout & getDataLayout() const
Get the data layout for the module&#39;s target platform.
Definition: Module.cpp:371
A Use represents the edge between a Value definition and its users.
Definition: Use.h:56
#define P(N)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
static bool IsStoredObjCPointer(const Value *P)
Test if the value of P, or any value covered by its provenance, is ever stored within the function (n...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
Definition: SmallPtrSet.h:371
const Value * getCondition() const
This file defines common analysis utilities used by the ObjC ARC Optimizer.
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
The two locations may or may not alias. This is the least precise result.
Definition: AliasAnalysis.h:86
The two locations precisely alias each other.
Definition: AliasAnalysis.h:90
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Definition: SmallPtrSet.h:418
This file declares a special form of Alias Analysis called ``Provenance Analysis&#39;&#39;.
This is a &#39;vector&#39; (really, a variable-sized array), optimized for the case when the array is small...
Definition: SmallVector.h:847
Module.h This file contains the declarations for the Module class.
LLVM_NODISCARD T pop_back_val()
Definition: SmallVector.h:381
const Value * GetUnderlyingObjCPtrCached(const Value *V, const DataLayout &DL, DenseMap< const Value *, WeakTrackingVH > &Cache)
A wrapper for GetUnderlyingObjCPtr used for results memoization.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
Definition: BitVector.h:941
bool related(const Value *A, const Value *B, const DataLayout &DL)
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Definition: Instruction.cpp:56
const Value * getFalseValue() const
LLVM_NODISCARD bool empty() const
Definition: SmallVector.h:56
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
LLVM Value Representation.
Definition: Value.h:73
The two locations alias, but only due to a partial overlap.
Definition: AliasAnalysis.h:88
op_range incoming_values()
const BasicBlock * getParent() const
Definition: Instruction.h:67