109467b48Spatrick //===- ProvenanceAnalysis.cpp - ObjC ARC Optimization ---------------------===//
209467b48Spatrick //
309467b48Spatrick // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
409467b48Spatrick // See https://llvm.org/LICENSE.txt for license information.
509467b48Spatrick // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
609467b48Spatrick //
709467b48Spatrick //===----------------------------------------------------------------------===//
809467b48Spatrick //
909467b48Spatrick /// \file
1009467b48Spatrick ///
1109467b48Spatrick /// This file defines a special form of Alias Analysis called ``Provenance
1209467b48Spatrick /// Analysis''. The word ``provenance'' refers to the history of the ownership
1309467b48Spatrick /// of an object. Thus ``Provenance Analysis'' is an analysis which attempts to
1409467b48Spatrick /// use various techniques to determine if locally
1509467b48Spatrick ///
1609467b48Spatrick /// WARNING: This file knows about certain library functions. It recognizes them
1709467b48Spatrick /// by name, and hardwires knowledge of their semantics.
1809467b48Spatrick ///
1909467b48Spatrick /// WARNING: This file knows about how certain Objective-C library functions are
2009467b48Spatrick /// used. Naive LLVM IR transformations which would otherwise be
2109467b48Spatrick /// behavior-preserving may break these assumptions.
2209467b48Spatrick //
2309467b48Spatrick //===----------------------------------------------------------------------===//
2409467b48Spatrick 
2509467b48Spatrick #include "ProvenanceAnalysis.h"
2609467b48Spatrick #include "llvm/ADT/SmallPtrSet.h"
2709467b48Spatrick #include "llvm/ADT/SmallVector.h"
2809467b48Spatrick #include "llvm/Analysis/AliasAnalysis.h"
2909467b48Spatrick #include "llvm/Analysis/ObjCARCAnalysisUtils.h"
3009467b48Spatrick #include "llvm/IR/Instructions.h"
3109467b48Spatrick #include "llvm/IR/Module.h"
3209467b48Spatrick #include "llvm/IR/Use.h"
3309467b48Spatrick #include "llvm/IR/User.h"
3409467b48Spatrick #include "llvm/IR/Value.h"
3509467b48Spatrick #include "llvm/Support/Casting.h"
3609467b48Spatrick #include <utility>
3709467b48Spatrick 
3809467b48Spatrick using namespace llvm;
3909467b48Spatrick using namespace llvm::objcarc;
4009467b48Spatrick 
relatedSelect(const SelectInst * A,const Value * B)4109467b48Spatrick bool ProvenanceAnalysis::relatedSelect(const SelectInst *A,
4209467b48Spatrick                                        const Value *B) {
4309467b48Spatrick   // If the values are Selects with the same condition, we can do a more precise
4409467b48Spatrick   // check: just check for relations between the values on corresponding arms.
45*d415bd75Srobert   if (const SelectInst *SB = dyn_cast<SelectInst>(B)) {
4609467b48Spatrick     if (A->getCondition() == SB->getCondition())
4773471bf0Spatrick       return related(A->getTrueValue(), SB->getTrueValue()) ||
4873471bf0Spatrick              related(A->getFalseValue(), SB->getFalseValue());
4909467b48Spatrick 
50*d415bd75Srobert     // Check both arms of B individually. Return false if neither arm is related
51*d415bd75Srobert     // to A.
52*d415bd75Srobert     if (!(related(SB->getTrueValue(), A) || related(SB->getFalseValue(), A)))
53*d415bd75Srobert       return false;
54*d415bd75Srobert   }
55*d415bd75Srobert 
5609467b48Spatrick   // Check both arms of the Select node individually.
5773471bf0Spatrick   return related(A->getTrueValue(), B) || related(A->getFalseValue(), B);
5809467b48Spatrick }
5909467b48Spatrick 
relatedPHI(const PHINode * A,const Value * B)6009467b48Spatrick bool ProvenanceAnalysis::relatedPHI(const PHINode *A,
6109467b48Spatrick                                     const Value *B) {
62*d415bd75Srobert 
63*d415bd75Srobert   auto comparePHISources = [this](const PHINode *PNA, const Value *B) -> bool {
64*d415bd75Srobert     // Check each unique source of the PHI node against B.
65*d415bd75Srobert     SmallPtrSet<const Value *, 4> UniqueSrc;
66*d415bd75Srobert     for (Value *PV1 : PNA->incoming_values()) {
67*d415bd75Srobert       if (UniqueSrc.insert(PV1).second && related(PV1, B))
68*d415bd75Srobert         return true;
69*d415bd75Srobert     }
70*d415bd75Srobert 
71*d415bd75Srobert     // All of the arms checked out.
72*d415bd75Srobert     return false;
73*d415bd75Srobert   };
74*d415bd75Srobert 
75*d415bd75Srobert   if (const PHINode *PNB = dyn_cast<PHINode>(B)) {
76*d415bd75Srobert     // If the values are PHIs in the same block, we can do a more precise as
77*d415bd75Srobert     // well as efficient check: just check for relations between the values on
7809467b48Spatrick     // corresponding edges.
7909467b48Spatrick     if (PNB->getParent() == A->getParent()) {
8009467b48Spatrick       for (unsigned i = 0, e = A->getNumIncomingValues(); i != e; ++i)
8109467b48Spatrick         if (related(A->getIncomingValue(i),
8273471bf0Spatrick                     PNB->getIncomingValueForBlock(A->getIncomingBlock(i))))
8309467b48Spatrick           return true;
8409467b48Spatrick       return false;
8509467b48Spatrick     }
8609467b48Spatrick 
87*d415bd75Srobert     if (!comparePHISources(PNB, A))
88*d415bd75Srobert       return false;
8909467b48Spatrick   }
9009467b48Spatrick 
91*d415bd75Srobert   return comparePHISources(A, B);
9209467b48Spatrick }
9309467b48Spatrick 
9409467b48Spatrick /// Test if the value of P, or any value covered by its provenance, is ever
9509467b48Spatrick /// stored within the function (not counting callees).
IsStoredObjCPointer(const Value * P)9609467b48Spatrick static bool IsStoredObjCPointer(const Value *P) {
9709467b48Spatrick   SmallPtrSet<const Value *, 8> Visited;
9809467b48Spatrick   SmallVector<const Value *, 8> Worklist;
9909467b48Spatrick   Worklist.push_back(P);
10009467b48Spatrick   Visited.insert(P);
10109467b48Spatrick   do {
10209467b48Spatrick     P = Worklist.pop_back_val();
10309467b48Spatrick     for (const Use &U : P->uses()) {
10409467b48Spatrick       const User *Ur = U.getUser();
10509467b48Spatrick       if (isa<StoreInst>(Ur)) {
10609467b48Spatrick         if (U.getOperandNo() == 0)
10709467b48Spatrick           // The pointer is stored.
10809467b48Spatrick           return true;
10909467b48Spatrick         // The pointed is stored through.
11009467b48Spatrick         continue;
11109467b48Spatrick       }
11209467b48Spatrick       if (isa<CallInst>(Ur))
11309467b48Spatrick         // The pointer is passed as an argument, ignore this.
11409467b48Spatrick         continue;
11509467b48Spatrick       if (isa<PtrToIntInst>(P))
11609467b48Spatrick         // Assume the worst.
11709467b48Spatrick         return true;
11809467b48Spatrick       if (Visited.insert(Ur).second)
11909467b48Spatrick         Worklist.push_back(Ur);
12009467b48Spatrick     }
12109467b48Spatrick   } while (!Worklist.empty());
12209467b48Spatrick 
12309467b48Spatrick   // Everything checked out.
12409467b48Spatrick   return false;
12509467b48Spatrick }
12609467b48Spatrick 
relatedCheck(const Value * A,const Value * B)12773471bf0Spatrick bool ProvenanceAnalysis::relatedCheck(const Value *A, const Value *B) {
12809467b48Spatrick   // Ask regular AliasAnalysis, for a first approximation.
12909467b48Spatrick   switch (AA->alias(A, B)) {
13073471bf0Spatrick   case AliasResult::NoAlias:
13109467b48Spatrick     return false;
13273471bf0Spatrick   case AliasResult::MustAlias:
13373471bf0Spatrick   case AliasResult::PartialAlias:
13409467b48Spatrick     return true;
13573471bf0Spatrick   case AliasResult::MayAlias:
13609467b48Spatrick     break;
13709467b48Spatrick   }
13809467b48Spatrick 
13909467b48Spatrick   bool AIsIdentified = IsObjCIdentifiedObject(A);
14009467b48Spatrick   bool BIsIdentified = IsObjCIdentifiedObject(B);
14109467b48Spatrick 
14209467b48Spatrick   // An ObjC-Identified object can't alias a load if it is never locally stored.
143*d415bd75Srobert 
14409467b48Spatrick   // Check for an obvious escape.
145*d415bd75Srobert   if ((AIsIdentified && isa<LoadInst>(B) && !IsStoredObjCPointer(A)) ||
146*d415bd75Srobert       (BIsIdentified && isa<LoadInst>(A) && !IsStoredObjCPointer(B)))
14709467b48Spatrick     return false;
148*d415bd75Srobert 
149*d415bd75Srobert   if ((AIsIdentified && isa<LoadInst>(B)) ||
150*d415bd75Srobert       (BIsIdentified && isa<LoadInst>(A)))
151*d415bd75Srobert     return true;
152*d415bd75Srobert 
153*d415bd75Srobert   // Both pointers are identified and escapes aren't an evident problem.
154*d415bd75Srobert   if (AIsIdentified && BIsIdentified && !isa<LoadInst>(A) && !isa<LoadInst>(B))
155*d415bd75Srobert     return false;
15609467b48Spatrick 
15709467b48Spatrick    // Special handling for PHI and Select.
15809467b48Spatrick   if (const PHINode *PN = dyn_cast<PHINode>(A))
15909467b48Spatrick     return relatedPHI(PN, B);
16009467b48Spatrick   if (const PHINode *PN = dyn_cast<PHINode>(B))
16109467b48Spatrick     return relatedPHI(PN, A);
16209467b48Spatrick   if (const SelectInst *S = dyn_cast<SelectInst>(A))
16309467b48Spatrick     return relatedSelect(S, B);
16409467b48Spatrick   if (const SelectInst *S = dyn_cast<SelectInst>(B))
16509467b48Spatrick     return relatedSelect(S, A);
16609467b48Spatrick 
16709467b48Spatrick   // Conservative.
16809467b48Spatrick   return true;
16909467b48Spatrick }
17009467b48Spatrick 
related(const Value * A,const Value * B)17173471bf0Spatrick bool ProvenanceAnalysis::related(const Value *A, const Value *B) {
17273471bf0Spatrick   A = GetUnderlyingObjCPtrCached(A, UnderlyingObjCPtrCache);
17373471bf0Spatrick   B = GetUnderlyingObjCPtrCached(B, UnderlyingObjCPtrCache);
17409467b48Spatrick 
17509467b48Spatrick   // Quick check.
17609467b48Spatrick   if (A == B)
17709467b48Spatrick     return true;
17809467b48Spatrick 
17909467b48Spatrick   // Begin by inserting a conservative value into the map. If the insertion
18009467b48Spatrick   // fails, we have the answer already. If it succeeds, leave it there until we
18109467b48Spatrick   // compute the real answer to guard against recursive queries.
18209467b48Spatrick   if (A > B) std::swap(A, B);
18309467b48Spatrick   std::pair<CachedResultsTy::iterator, bool> Pair =
18409467b48Spatrick     CachedResults.insert(std::make_pair(ValuePairTy(A, B), true));
18509467b48Spatrick   if (!Pair.second)
18609467b48Spatrick     return Pair.first->second;
18709467b48Spatrick 
18873471bf0Spatrick   bool Result = relatedCheck(A, B);
189*d415bd75Srobert   assert(relatedCheck(B, A) == Result &&
190*d415bd75Srobert          "relatedCheck result depending on order of parameters!");
19109467b48Spatrick   CachedResults[ValuePairTy(A, B)] = Result;
19209467b48Spatrick   return Result;
19309467b48Spatrick }
194