ProvenanceAnalysis.cpp 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. //===- ProvenanceAnalysis.cpp - ObjC ARC Optimization ---------------------===//
  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. /// \file
  10. ///
  11. /// This file defines a special form of Alias Analysis called ``Provenance
  12. /// Analysis''. The word ``provenance'' refers to the history of the ownership
  13. /// of an object. Thus ``Provenance Analysis'' is an analysis which attempts to
  14. /// use various techniques to determine if locally
  15. ///
  16. /// WARNING: This file knows about certain library functions. It recognizes them
  17. /// by name, and hardwires knowledge of their semantics.
  18. ///
  19. /// WARNING: This file knows about how certain Objective-C library functions are
  20. /// used. Naive LLVM IR transformations which would otherwise be
  21. /// behavior-preserving may break these assumptions.
  22. //
  23. //===----------------------------------------------------------------------===//
  24. #include "ProvenanceAnalysis.h"
  25. #include "llvm/ADT/SmallPtrSet.h"
  26. #include "llvm/ADT/SmallVector.h"
  27. #include "llvm/Analysis/AliasAnalysis.h"
  28. #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
  29. #include "llvm/IR/Instructions.h"
  30. #include "llvm/IR/Module.h"
  31. #include "llvm/IR/Use.h"
  32. #include "llvm/IR/User.h"
  33. #include "llvm/IR/Value.h"
  34. #include "llvm/Support/Casting.h"
  35. #include <utility>
  36. using namespace llvm;
  37. using namespace llvm::objcarc;
  38. bool ProvenanceAnalysis::relatedSelect(const SelectInst *A,
  39. const Value *B) {
  40. // If the values are Selects with the same condition, we can do a more precise
  41. // check: just check for relations between the values on corresponding arms.
  42. if (const SelectInst *SB = dyn_cast<SelectInst>(B)) {
  43. if (A->getCondition() == SB->getCondition())
  44. return related(A->getTrueValue(), SB->getTrueValue()) ||
  45. related(A->getFalseValue(), SB->getFalseValue());
  46. // Check both arms of B individually. Return false if neither arm is related
  47. // to A.
  48. if (!(related(SB->getTrueValue(), A) || related(SB->getFalseValue(), A)))
  49. return false;
  50. }
  51. // Check both arms of the Select node individually.
  52. return related(A->getTrueValue(), B) || related(A->getFalseValue(), B);
  53. }
  54. bool ProvenanceAnalysis::relatedPHI(const PHINode *A,
  55. const Value *B) {
  56. auto comparePHISources = [this](const PHINode *PNA, const Value *B) -> bool {
  57. // Check each unique source of the PHI node against B.
  58. SmallPtrSet<const Value *, 4> UniqueSrc;
  59. for (Value *PV1 : PNA->incoming_values()) {
  60. if (UniqueSrc.insert(PV1).second && related(PV1, B))
  61. return true;
  62. }
  63. // All of the arms checked out.
  64. return false;
  65. };
  66. if (const PHINode *PNB = dyn_cast<PHINode>(B)) {
  67. // If the values are PHIs in the same block, we can do a more precise as
  68. // well as efficient check: just check for relations between the values on
  69. // corresponding edges.
  70. if (PNB->getParent() == A->getParent()) {
  71. for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
  72. if (related(A->getIncomingValue(i),
  73. PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
  74. return true;
  75. return false;
  76. }
  77. if (!comparePHISources(PNB, A))
  78. return false;
  79. }
  80. return comparePHISources(A, B);
  81. }
  82. /// Test if the value of P, or any value covered by its provenance, is ever
  83. /// stored within the function (not counting callees).
  84. static bool IsStoredObjCPointer(const Value *P) {
  85. SmallPtrSet<const Value *, 8> Visited;
  86. SmallVector<const Value *, 8> Worklist;
  87. Worklist.push_back(P);
  88. Visited.insert(P);
  89. do {
  90. P = Worklist.pop_back_val();
  91. for (const Use &U : P->uses()) {
  92. const User *Ur = U.getUser();
  93. if (isa<StoreInst>(Ur)) {
  94. if (U.getOperandNo() == 0)
  95. // The pointer is stored.
  96. return true;
  97. // The pointed is stored through.
  98. continue;
  99. }
  100. if (isa<CallInst>(Ur))
  101. // The pointer is passed as an argument, ignore this.
  102. continue;
  103. if (isa<PtrToIntInst>(P))
  104. // Assume the worst.
  105. return true;
  106. if (Visited.insert(Ur).second)
  107. Worklist.push_back(Ur);
  108. }
  109. } while (!Worklist.empty());
  110. // Everything checked out.
  111. return false;
  112. }
  113. bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
  114. // Ask regular AliasAnalysis, for a first approximation.
  115. switch (AA->alias(A, B)) {
  116. case AliasResult::NoAlias:
  117. return false;
  118. case AliasResult::MustAlias:
  119. case AliasResult::PartialAlias:
  120. return true;
  121. case AliasResult::MayAlias:
  122. break;
  123. }
  124. bool AIsIdentified = IsObjCIdentifiedObject(A);
  125. bool BIsIdentified = IsObjCIdentifiedObject(B);
  126. // An ObjC-Identified object can't alias a load if it is never locally stored.
  127. // Check for an obvious escape.
  128. if ((AIsIdentified && isa<LoadInst>(B) && !IsStoredObjCPointer(A)) ||
  129. (BIsIdentified && isa<LoadInst>(A) && !IsStoredObjCPointer(B)))
  130. return false;
  131. if ((AIsIdentified && isa<LoadInst>(B)) ||
  132. (BIsIdentified && isa<LoadInst>(A)))
  133. return true;
  134. // Both pointers are identified and escapes aren't an evident problem.
  135. if (AIsIdentified && BIsIdentified && !isa<LoadInst>(A) && !isa<LoadInst>(B))
  136. return false;
  137. // Special handling for PHI and Select.
  138. if (const PHINode *PN = dyn_cast<PHINode>(A))
  139. return relatedPHI(PN, B);
  140. if (const PHINode *PN = dyn_cast<PHINode>(B))
  141. return relatedPHI(PN, A);
  142. if (const SelectInst *S = dyn_cast<SelectInst>(A))
  143. return relatedSelect(S, B);
  144. if (const SelectInst *S = dyn_cast<SelectInst>(B))
  145. return relatedSelect(S, A);
  146. // Conservative.
  147. return true;
  148. }
  149. bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
  150. A = GetUnderlyingObjCPtrCached(A, UnderlyingObjCPtrCache);
  151. B = GetUnderlyingObjCPtrCached(B, UnderlyingObjCPtrCache);
  152. // Quick check.
  153. if (A == B)
  154. return true;
  155. // Begin by inserting a conservative value into the map. If the insertion
  156. // fails, we have the answer already. If it succeeds, leave it there until we
  157. // compute the real answer to guard against recursive queries.
  158. if (A > B) std::swap(A, B);
  159. std::pair<CachedResultsTy::iterator, bool> Pair =
  160. CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
  161. if (!Pair.second)
  162. return Pair.first->second;
  163. bool Result = relatedCheck(A, B);
  164. assert(relatedCheck(B, A) == Result &&
  165. "relatedCheck result depending on order of parameters!");
  166. CachedResults[ValuePairTy(A, B)] = Result;
  167. return Result;
  168. }