1f785676fSDimitry Andric //===- MemoryDependenceAnalysis.cpp - Mem Deps Implementation -------------===//
2f22ef01cSRoman Divacky //
3f22ef01cSRoman Divacky //                     The LLVM Compiler Infrastructure
4f22ef01cSRoman Divacky //
5f22ef01cSRoman Divacky // This file is distributed under the University of Illinois Open Source
6f22ef01cSRoman Divacky // License. See LICENSE.TXT for details.
7f22ef01cSRoman Divacky //
8f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
9f22ef01cSRoman Divacky //
10f22ef01cSRoman Divacky // This file implements an analysis that determines, for a given memory
11f22ef01cSRoman Divacky // operation, what preceding memory operations it depends on.  It builds on
12f22ef01cSRoman Divacky // alias analysis information, and tries to provide a lazy, caching interface to
13f22ef01cSRoman Divacky // a common kind of alias information query.
14f22ef01cSRoman Divacky //
15f22ef01cSRoman Divacky //===----------------------------------------------------------------------===//
16f22ef01cSRoman Divacky 
17f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryDependenceAnalysis.h"
182cab237bSDimitry Andric #include "llvm/ADT/DenseMap.h"
19db17bf38SDimitry Andric #include "llvm/ADT/STLExtras.h"
202cab237bSDimitry Andric #include "llvm/ADT/SmallPtrSet.h"
21d88c1a5aSDimitry Andric #include "llvm/ADT/SmallVector.h"
22139f7f9bSDimitry Andric #include "llvm/ADT/Statistic.h"
23f22ef01cSRoman Divacky #include "llvm/Analysis/AliasAnalysis.h"
2439d628a0SDimitry Andric #include "llvm/Analysis/AssumptionCache.h"
25f22ef01cSRoman Divacky #include "llvm/Analysis/MemoryBuiltins.h"
262cab237bSDimitry Andric #include "llvm/Analysis/MemoryLocation.h"
277d523365SDimitry Andric #include "llvm/Analysis/OrderedBasicBlock.h"
28db17bf38SDimitry Andric #include "llvm/Analysis/PHITransAddr.h"
294ba319b5SDimitry Andric #include "llvm/Analysis/PhiValues.h"
307d523365SDimitry Andric #include "llvm/Analysis/TargetLibraryInfo.h"
31db17bf38SDimitry Andric #include "llvm/Analysis/ValueTracking.h"
322cab237bSDimitry Andric #include "llvm/IR/Attributes.h"
332cab237bSDimitry Andric #include "llvm/IR/BasicBlock.h"
34d88c1a5aSDimitry Andric #include "llvm/IR/Constants.h"
35139f7f9bSDimitry Andric #include "llvm/IR/DataLayout.h"
36d88c1a5aSDimitry Andric #include "llvm/IR/DerivedTypes.h"
3791bc56edSDimitry Andric #include "llvm/IR/Dominators.h"
38139f7f9bSDimitry Andric #include "llvm/IR/Function.h"
392cab237bSDimitry Andric #include "llvm/IR/InstrTypes.h"
40d88c1a5aSDimitry Andric #include "llvm/IR/Instruction.h"
41139f7f9bSDimitry Andric #include "llvm/IR/Instructions.h"
42139f7f9bSDimitry Andric #include "llvm/IR/IntrinsicInst.h"
43139f7f9bSDimitry Andric #include "llvm/IR/LLVMContext.h"
442cab237bSDimitry Andric #include "llvm/IR/Metadata.h"
452cab237bSDimitry Andric #include "llvm/IR/Module.h"
4691bc56edSDimitry Andric #include "llvm/IR/PredIteratorCache.h"
472cab237bSDimitry Andric #include "llvm/IR/Type.h"
482cab237bSDimitry Andric #include "llvm/IR/Use.h"
492cab237bSDimitry Andric #include "llvm/IR/User.h"
502cab237bSDimitry Andric #include "llvm/IR/Value.h"
512cab237bSDimitry Andric #include "llvm/Pass.h"
52d88c1a5aSDimitry Andric #include "llvm/Support/AtomicOrdering.h"
53d88c1a5aSDimitry Andric #include "llvm/Support/Casting.h"
54d88c1a5aSDimitry Andric #include "llvm/Support/CommandLine.h"
55d88c1a5aSDimitry Andric #include "llvm/Support/Compiler.h"
56f22ef01cSRoman Divacky #include "llvm/Support/Debug.h"
57d88c1a5aSDimitry Andric #include "llvm/Support/MathExtras.h"
58d88c1a5aSDimitry Andric #include <algorithm>
59d88c1a5aSDimitry Andric #include <cassert>
602cab237bSDimitry Andric #include <cstdint>
61d88c1a5aSDimitry Andric #include <iterator>
622cab237bSDimitry Andric #include <utility>
63d88c1a5aSDimitry Andric 
64f22ef01cSRoman Divacky using namespace llvm;
65f22ef01cSRoman Divacky 
6691bc56edSDimitry Andric #define DEBUG_TYPE "memdep"
6791bc56edSDimitry Andric 
68f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
69f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
70f22ef01cSRoman Divacky STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
71f22ef01cSRoman Divacky 
72f22ef01cSRoman Divacky STATISTIC(NumCacheNonLocalPtr,
73f22ef01cSRoman Divacky           "Number of fully cached non-local ptr responses");
74f22ef01cSRoman Divacky STATISTIC(NumCacheDirtyNonLocalPtr,
75f22ef01cSRoman Divacky           "Number of cached, but dirty, non-local ptr responses");
763ca95b02SDimitry Andric STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
77f22ef01cSRoman Divacky STATISTIC(NumCacheCompleteNonLocalPtr,
78f22ef01cSRoman Divacky           "Number of block queries that were completely cached");
79f22ef01cSRoman Divacky 
8017a519f9SDimitry Andric // Limit for the number of instructions to scan in a block.
817d523365SDimitry Andric 
827d523365SDimitry Andric static cl::opt<unsigned> BlockScanLimit(
837d523365SDimitry Andric     "memdep-block-scan-limit", cl::Hidden, cl::init(100),
847d523365SDimitry Andric     cl::desc("The number of instructions to scan in a block in memory "
857d523365SDimitry Andric              "dependency analysis (default = 100)"));
8639d628a0SDimitry Andric 
873ca95b02SDimitry Andric static cl::opt<unsigned>
883ca95b02SDimitry Andric     BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000),
893ca95b02SDimitry Andric                      cl::desc("The number of blocks to scan during memory "
903ca95b02SDimitry Andric                               "dependency analysis (default = 1000)"));
913ca95b02SDimitry Andric 
9239d628a0SDimitry Andric // Limit on the number of memdep results to process.
9339d628a0SDimitry Andric static const unsigned int NumResultsLimit = 100;
9417a519f9SDimitry Andric 
953ca95b02SDimitry Andric /// This is a helper function that removes Val from 'Inst's set in ReverseMap.
96f22ef01cSRoman Divacky ///
973ca95b02SDimitry Andric /// If the set becomes empty, remove Inst's entry.
98f22ef01cSRoman Divacky template <typename KeyTy>
993ca95b02SDimitry Andric static void
RemoveFromReverseMap(DenseMap<Instruction *,SmallPtrSet<KeyTy,4>> & ReverseMap,Instruction * Inst,KeyTy Val)1003ca95b02SDimitry Andric RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
101f22ef01cSRoman Divacky                      Instruction *Inst, KeyTy Val) {
1023ca95b02SDimitry Andric   typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
1033ca95b02SDimitry Andric       ReverseMap.find(Inst);
104f22ef01cSRoman Divacky   assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
105f22ef01cSRoman Divacky   bool Found = InstIt->second.erase(Val);
1063ca95b02SDimitry Andric   assert(Found && "Invalid reverse map!");
1073ca95b02SDimitry Andric   (void)Found;
108f22ef01cSRoman Divacky   if (InstIt->second.empty())
109f22ef01cSRoman Divacky     ReverseMap.erase(InstIt);
110f22ef01cSRoman Divacky }
111f22ef01cSRoman Divacky 
1123ca95b02SDimitry Andric /// If the given instruction references a specific memory location, fill in Loc
1133ca95b02SDimitry Andric /// with the details, otherwise set Loc.Ptr to null.
1143ca95b02SDimitry Andric ///
1153ca95b02SDimitry Andric /// Returns a ModRefInfo value describing the general behavior of the
1162754fe60SDimitry Andric /// instruction.
GetLocation(const Instruction * Inst,MemoryLocation & Loc,const TargetLibraryInfo & TLI)1177d523365SDimitry Andric static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
1187d523365SDimitry Andric                               const TargetLibraryInfo &TLI) {
1192754fe60SDimitry Andric   if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
1206122f3e6SDimitry Andric     if (LI->isUnordered()) {
12197bc6c73SDimitry Andric       Loc = MemoryLocation::get(LI);
1222cab237bSDimitry Andric       return ModRefInfo::Ref;
123139f7f9bSDimitry Andric     }
1243ca95b02SDimitry Andric     if (LI->getOrdering() == AtomicOrdering::Monotonic) {
12597bc6c73SDimitry Andric       Loc = MemoryLocation::get(LI);
1262cab237bSDimitry Andric       return ModRefInfo::ModRef;
1276122f3e6SDimitry Andric     }
1288f0fd8f6SDimitry Andric     Loc = MemoryLocation();
1292cab237bSDimitry Andric     return ModRefInfo::ModRef;
1302754fe60SDimitry Andric   }
1312754fe60SDimitry Andric 
1322754fe60SDimitry Andric   if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
1336122f3e6SDimitry Andric     if (SI->isUnordered()) {
13497bc6c73SDimitry Andric       Loc = MemoryLocation::get(SI);
1352cab237bSDimitry Andric       return ModRefInfo::Mod;
136139f7f9bSDimitry Andric     }
1373ca95b02SDimitry Andric     if (SI->getOrdering() == AtomicOrdering::Monotonic) {
13897bc6c73SDimitry Andric       Loc = MemoryLocation::get(SI);
1392cab237bSDimitry Andric       return ModRefInfo::ModRef;
1406122f3e6SDimitry Andric     }
1418f0fd8f6SDimitry Andric     Loc = MemoryLocation();
1422cab237bSDimitry Andric     return ModRefInfo::ModRef;
1432754fe60SDimitry Andric   }
1442754fe60SDimitry Andric 
1452754fe60SDimitry Andric   if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
14697bc6c73SDimitry Andric     Loc = MemoryLocation::get(V);
1472cab237bSDimitry Andric     return ModRefInfo::ModRef;
1482754fe60SDimitry Andric   }
1492754fe60SDimitry Andric 
1507d523365SDimitry Andric   if (const CallInst *CI = isFreeCall(Inst, &TLI)) {
1512754fe60SDimitry Andric     // calls to free() deallocate the entire structure
1528f0fd8f6SDimitry Andric     Loc = MemoryLocation(CI->getArgOperand(0));
1532cab237bSDimitry Andric     return ModRefInfo::Mod;
1542754fe60SDimitry Andric   }
1552754fe60SDimitry Andric 
15639d628a0SDimitry Andric   if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
1572754fe60SDimitry Andric     switch (II->getIntrinsicID()) {
1582754fe60SDimitry Andric     case Intrinsic::lifetime_start:
1592754fe60SDimitry Andric     case Intrinsic::lifetime_end:
1602754fe60SDimitry Andric     case Intrinsic::invariant_start:
1614ba319b5SDimitry Andric       Loc = MemoryLocation::getForArgument(II, 1, TLI);
1622754fe60SDimitry Andric       // These intrinsics don't really modify the memory, but returning Mod
1632754fe60SDimitry Andric       // will allow them to be handled conservatively.
1642cab237bSDimitry Andric       return ModRefInfo::Mod;
1652754fe60SDimitry Andric     case Intrinsic::invariant_end:
1664ba319b5SDimitry Andric       Loc = MemoryLocation::getForArgument(II, 2, TLI);
1672754fe60SDimitry Andric       // These intrinsics don't really modify the memory, but returning Mod
1682754fe60SDimitry Andric       // will allow them to be handled conservatively.
1692cab237bSDimitry Andric       return ModRefInfo::Mod;
1702754fe60SDimitry Andric     default:
1712754fe60SDimitry Andric       break;
1722754fe60SDimitry Andric     }
17339d628a0SDimitry Andric   }
1742754fe60SDimitry Andric 
1752754fe60SDimitry Andric   // Otherwise, just do the coarse-grained thing that always works.
1762754fe60SDimitry Andric   if (Inst->mayWriteToMemory())
1772cab237bSDimitry Andric     return ModRefInfo::ModRef;
1782754fe60SDimitry Andric   if (Inst->mayReadFromMemory())
1792cab237bSDimitry Andric     return ModRefInfo::Ref;
1802cab237bSDimitry Andric   return ModRefInfo::NoModRef;
1812754fe60SDimitry Andric }
182f22ef01cSRoman Divacky 
1833ca95b02SDimitry Andric /// Private helper for finding the local dependencies of a call site.
getCallDependencyFrom(CallBase * Call,bool isReadOnlyCall,BasicBlock::iterator ScanIt,BasicBlock * BB)184*b5893f02SDimitry Andric MemDepResult MemoryDependenceResults::getCallDependencyFrom(
185*b5893f02SDimitry Andric     CallBase *Call, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
1863ca95b02SDimitry Andric     BasicBlock *BB) {
18717a519f9SDimitry Andric   unsigned Limit = BlockScanLimit;
18817a519f9SDimitry Andric 
189d88c1a5aSDimitry Andric   // Walk backwards through the block, looking for dependencies.
190f22ef01cSRoman Divacky   while (ScanIt != BB->begin()) {
1912cab237bSDimitry Andric     Instruction *Inst = &*--ScanIt;
1922cab237bSDimitry Andric     // Debug intrinsics don't cause dependences and should not affect Limit
1932cab237bSDimitry Andric     if (isa<DbgInfoIntrinsic>(Inst))
1942cab237bSDimitry Andric       continue;
1952cab237bSDimitry Andric 
19617a519f9SDimitry Andric     // Limit the amount of scanning we do so we don't end up with quadratic
19717a519f9SDimitry Andric     // running time on extreme testcases.
19817a519f9SDimitry Andric     --Limit;
19917a519f9SDimitry Andric     if (!Limit)
20017a519f9SDimitry Andric       return MemDepResult::getUnknown();
20117a519f9SDimitry Andric 
202f22ef01cSRoman Divacky     // If this inst is a memory op, get the pointer it accessed
2038f0fd8f6SDimitry Andric     MemoryLocation Loc;
2043ca95b02SDimitry Andric     ModRefInfo MR = GetLocation(Inst, Loc, TLI);
2052754fe60SDimitry Andric     if (Loc.Ptr) {
2062754fe60SDimitry Andric       // A simple instruction.
207*b5893f02SDimitry Andric       if (isModOrRefSet(AA.getModRefInfo(Call, Loc)))
2082754fe60SDimitry Andric         return MemDepResult::getClobber(Inst);
2092754fe60SDimitry Andric       continue;
2102754fe60SDimitry Andric     }
2112754fe60SDimitry Andric 
212*b5893f02SDimitry Andric     if (auto *CallB = dyn_cast<CallBase>(Inst)) {
213f22ef01cSRoman Divacky       // If these two calls do not interfere, look past it.
214*b5893f02SDimitry Andric       if (isNoModRef(AA.getModRefInfo(Call, CallB))) {
215*b5893f02SDimitry Andric         // If the two calls are the same, return Inst as a Def, so that
216*b5893f02SDimitry Andric         // Call can be found redundant and eliminated.
2172cab237bSDimitry Andric         if (isReadOnlyCall && !isModSet(MR) &&
218*b5893f02SDimitry Andric             Call->isIdenticalToWhenDefined(CallB))
219f22ef01cSRoman Divacky           return MemDepResult::getDef(Inst);
220e580952dSDimitry Andric 
221*b5893f02SDimitry Andric         // Otherwise if the two calls don't interact (e.g. CallB is readnone)
222e580952dSDimitry Andric         // keep scanning.
2237ae0e2c9SDimitry Andric         continue;
2242cab237bSDimitry Andric       } else
225f22ef01cSRoman Divacky         return MemDepResult::getClobber(Inst);
226f22ef01cSRoman Divacky     }
2277ae0e2c9SDimitry Andric 
2287ae0e2c9SDimitry Andric     // If we could not obtain a pointer for the instruction and the instruction
2297ae0e2c9SDimitry Andric     // touches memory then assume that this is a dependency.
2302cab237bSDimitry Andric     if (isModOrRefSet(MR))
2317ae0e2c9SDimitry Andric       return MemDepResult::getClobber(Inst);
232f22ef01cSRoman Divacky   }
233f22ef01cSRoman Divacky 
23417a519f9SDimitry Andric   // No dependence found.  If this is the entry block of the function, it is
23517a519f9SDimitry Andric   // unknown, otherwise it is non-local.
236f22ef01cSRoman Divacky   if (BB != &BB->getParent()->getEntryBlock())
237f22ef01cSRoman Divacky     return MemDepResult::getNonLocal();
2386122f3e6SDimitry Andric   return MemDepResult::getNonFuncLocal();
239f22ef01cSRoman Divacky }
240f22ef01cSRoman Divacky 
getLoadLoadClobberFullWidthSize(const Value * MemLocBase,int64_t MemLocOffs,unsigned MemLocSize,const LoadInst * LI)2413ca95b02SDimitry Andric unsigned MemoryDependenceResults::getLoadLoadClobberFullWidthSize(
242ff0cc061SDimitry Andric     const Value *MemLocBase, int64_t MemLocOffs, unsigned MemLocSize,
243ff0cc061SDimitry Andric     const LoadInst *LI) {
2446122f3e6SDimitry Andric   // We can only extend simple integer loads.
2453ca95b02SDimitry Andric   if (!isa<IntegerType>(LI->getType()) || !LI->isSimple())
2463ca95b02SDimitry Andric     return 0;
2473b0f4066SDimitry Andric 
248139f7f9bSDimitry Andric   // Load widening is hostile to ThreadSanitizer: it may cause false positives
249139f7f9bSDimitry Andric   // or make the reports more cryptic (access sizes are wrong).
250ff0cc061SDimitry Andric   if (LI->getParent()->getParent()->hasFnAttribute(Attribute::SanitizeThread))
251139f7f9bSDimitry Andric     return 0;
252139f7f9bSDimitry Andric 
253ff0cc061SDimitry Andric   const DataLayout &DL = LI->getModule()->getDataLayout();
254ff0cc061SDimitry Andric 
2553b0f4066SDimitry Andric   // Get the base of this load.
2563b0f4066SDimitry Andric   int64_t LIOffs = 0;
2573b0f4066SDimitry Andric   const Value *LIBase =
258ff0cc061SDimitry Andric       GetPointerBaseWithConstantOffset(LI->getPointerOperand(), LIOffs, DL);
2593b0f4066SDimitry Andric 
2603b0f4066SDimitry Andric   // If the two pointers are not based on the same pointer, we can't tell that
2613b0f4066SDimitry Andric   // they are related.
2623ca95b02SDimitry Andric   if (LIBase != MemLocBase)
2633ca95b02SDimitry Andric     return 0;
2643b0f4066SDimitry Andric 
2653b0f4066SDimitry Andric   // Okay, the two values are based on the same pointer, but returned as
2663b0f4066SDimitry Andric   // no-alias.  This happens when we have things like two byte loads at "P+1"
2673b0f4066SDimitry Andric   // and "P+3".  Check to see if increasing the size of the "LI" load up to its
2683b0f4066SDimitry Andric   // alignment (or the largest native integer type) will allow us to load all
2693b0f4066SDimitry Andric   // the bits required by MemLoc.
2703b0f4066SDimitry Andric 
2713b0f4066SDimitry Andric   // If MemLoc is before LI, then no widening of LI will help us out.
2723ca95b02SDimitry Andric   if (MemLocOffs < LIOffs)
2733ca95b02SDimitry Andric     return 0;
2743b0f4066SDimitry Andric 
2753b0f4066SDimitry Andric   // Get the alignment of the load in bytes.  We assume that it is safe to load
2763b0f4066SDimitry Andric   // any legal integer up to this size without a problem.  For example, if we're
2773b0f4066SDimitry Andric   // looking at an i8 load on x86-32 that is known 1024 byte aligned, we can
2783b0f4066SDimitry Andric   // widen it up to an i32 load.  If it is known 2-byte aligned, we can widen it
2793b0f4066SDimitry Andric   // to i16.
2803b0f4066SDimitry Andric   unsigned LoadAlign = LI->getAlignment();
2813b0f4066SDimitry Andric 
2823b0f4066SDimitry Andric   int64_t MemLocEnd = MemLocOffs + MemLocSize;
2833b0f4066SDimitry Andric 
2843b0f4066SDimitry Andric   // If no amount of rounding up will let MemLoc fit into LI, then bail out.
2853ca95b02SDimitry Andric   if (LIOffs + LoadAlign < MemLocEnd)
2863ca95b02SDimitry Andric     return 0;
2873b0f4066SDimitry Andric 
2883b0f4066SDimitry Andric   // This is the size of the load to try.  Start with the next larger power of
2893b0f4066SDimitry Andric   // two.
2903b0f4066SDimitry Andric   unsigned NewLoadByteSize = LI->getType()->getPrimitiveSizeInBits() / 8U;
2913b0f4066SDimitry Andric   NewLoadByteSize = NextPowerOf2(NewLoadByteSize);
2923b0f4066SDimitry Andric 
293d88c1a5aSDimitry Andric   while (true) {
2943b0f4066SDimitry Andric     // If this load size is bigger than our known alignment or would not fit
2953b0f4066SDimitry Andric     // into a native integer register, then we fail.
2963b0f4066SDimitry Andric     if (NewLoadByteSize > LoadAlign ||
29791bc56edSDimitry Andric         !DL.fitsInLegalInteger(NewLoadByteSize * 8))
2983b0f4066SDimitry Andric       return 0;
2993b0f4066SDimitry Andric 
300dff0c46cSDimitry Andric     if (LIOffs + NewLoadByteSize > MemLocEnd &&
3012cab237bSDimitry Andric         (LI->getParent()->getParent()->hasFnAttribute(
3022cab237bSDimitry Andric              Attribute::SanitizeAddress) ||
303ff0cc061SDimitry Andric          LI->getParent()->getParent()->hasFnAttribute(
3042cab237bSDimitry Andric              Attribute::SanitizeHWAddress)))
305dff0c46cSDimitry Andric       // We will be reading past the location accessed by the original program.
306dff0c46cSDimitry Andric       // While this is safe in a regular build, Address Safety analysis tools
307dff0c46cSDimitry Andric       // may start reporting false warnings. So, don't do widening.
308dff0c46cSDimitry Andric       return 0;
309dff0c46cSDimitry Andric 
3103b0f4066SDimitry Andric     // If a load of this width would include all of MemLoc, then we succeed.
3113b0f4066SDimitry Andric     if (LIOffs + NewLoadByteSize >= MemLocEnd)
3123b0f4066SDimitry Andric       return NewLoadByteSize;
3133b0f4066SDimitry Andric 
3143b0f4066SDimitry Andric     NewLoadByteSize <<= 1;
3153b0f4066SDimitry Andric   }
316dff0c46cSDimitry Andric }
3173b0f4066SDimitry Andric 
isVolatile(Instruction * Inst)318ff0cc061SDimitry Andric static bool isVolatile(Instruction *Inst) {
319edd7eaddSDimitry Andric   if (auto *LI = dyn_cast<LoadInst>(Inst))
320ff0cc061SDimitry Andric     return LI->isVolatile();
321edd7eaddSDimitry Andric   if (auto *SI = dyn_cast<StoreInst>(Inst))
322ff0cc061SDimitry Andric     return SI->isVolatile();
323edd7eaddSDimitry Andric   if (auto *AI = dyn_cast<AtomicCmpXchgInst>(Inst))
324ff0cc061SDimitry Andric     return AI->isVolatile();
325ff0cc061SDimitry Andric   return false;
326ff0cc061SDimitry Andric }
327ff0cc061SDimitry Andric 
getPointerDependencyFrom(const MemoryLocation & MemLoc,bool isLoad,BasicBlock::iterator ScanIt,BasicBlock * BB,Instruction * QueryInst,unsigned * Limit)3283ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
3298f0fd8f6SDimitry Andric     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
330d88c1a5aSDimitry Andric     BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
331f1a29dd3SDimitry Andric   MemDepResult InvariantGroupDependency = MemDepResult::getUnknown();
3327d523365SDimitry Andric   if (QueryInst != nullptr) {
3337d523365SDimitry Andric     if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
334f1a29dd3SDimitry Andric       InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB);
3357d523365SDimitry Andric 
336f1a29dd3SDimitry Andric       if (InvariantGroupDependency.isDef())
337f1a29dd3SDimitry Andric         return InvariantGroupDependency;
3387d523365SDimitry Andric     }
3397d523365SDimitry Andric   }
340f1a29dd3SDimitry Andric   MemDepResult SimpleDep = getSimplePointerDependencyFrom(
341f1a29dd3SDimitry Andric       MemLoc, isLoad, ScanIt, BB, QueryInst, Limit);
342f1a29dd3SDimitry Andric   if (SimpleDep.isDef())
343f1a29dd3SDimitry Andric     return SimpleDep;
344f1a29dd3SDimitry Andric   // Non-local invariant group dependency indicates there is non local Def
345f1a29dd3SDimitry Andric   // (it only returns nonLocal if it finds nonLocal def), which is better than
346f1a29dd3SDimitry Andric   // local clobber and everything else.
347f1a29dd3SDimitry Andric   if (InvariantGroupDependency.isNonLocal())
348f1a29dd3SDimitry Andric     return InvariantGroupDependency;
349f1a29dd3SDimitry Andric 
350f1a29dd3SDimitry Andric   assert(InvariantGroupDependency.isUnknown() &&
351f1a29dd3SDimitry Andric          "InvariantGroupDependency should be only unknown at this point");
352f1a29dd3SDimitry Andric   return SimpleDep;
3537d523365SDimitry Andric }
3547d523365SDimitry Andric 
3557d523365SDimitry Andric MemDepResult
getInvariantGroupPointerDependency(LoadInst * LI,BasicBlock * BB)3563ca95b02SDimitry Andric MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
3577d523365SDimitry Andric                                                             BasicBlock *BB) {
3584ba319b5SDimitry Andric 
3594ba319b5SDimitry Andric   if (!LI->getMetadata(LLVMContext::MD_invariant_group))
360d88c1a5aSDimitry Andric     return MemDepResult::getUnknown();
361d88c1a5aSDimitry Andric 
36224e2fe98SDimitry Andric   // Take the ptr operand after all casts and geps 0. This way we can search
36324e2fe98SDimitry Andric   // cast graph down only.
36424e2fe98SDimitry Andric   Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
36524e2fe98SDimitry Andric 
3667d523365SDimitry Andric   // It's is not safe to walk the use list of global value, because function
3677d523365SDimitry Andric   // passes aren't allowed to look outside their functions.
36824e2fe98SDimitry Andric   // FIXME: this could be fixed by filtering instructions from outside
36924e2fe98SDimitry Andric   // of current function.
3707d523365SDimitry Andric   if (isa<GlobalValue>(LoadOperand))
3717d523365SDimitry Andric     return MemDepResult::getUnknown();
3727d523365SDimitry Andric 
3737d523365SDimitry Andric   // Queue to process all pointers that are equivalent to load operand.
374d88c1a5aSDimitry Andric   SmallVector<const Value *, 8> LoadOperandsQueue;
37524e2fe98SDimitry Andric   LoadOperandsQueue.push_back(LoadOperand);
376f1a29dd3SDimitry Andric 
377f1a29dd3SDimitry Andric   Instruction *ClosestDependency = nullptr;
378f1a29dd3SDimitry Andric   // Order of instructions in uses list is unpredictible. In order to always
379f1a29dd3SDimitry Andric   // get the same result, we will look for the closest dominance.
380f1a29dd3SDimitry Andric   auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) {
381f1a29dd3SDimitry Andric     assert(Other && "Must call it with not null instruction");
382f1a29dd3SDimitry Andric     if (Best == nullptr || DT.dominates(Best, Other))
383f1a29dd3SDimitry Andric       return Other;
384f1a29dd3SDimitry Andric     return Best;
385f1a29dd3SDimitry Andric   };
386f1a29dd3SDimitry Andric 
387f1a29dd3SDimitry Andric   // FIXME: This loop is O(N^2) because dominates can be O(n) and in worst case
388f1a29dd3SDimitry Andric   // we will see all the instructions. This should be fixed in MSSA.
3897d523365SDimitry Andric   while (!LoadOperandsQueue.empty()) {
390d88c1a5aSDimitry Andric     const Value *Ptr = LoadOperandsQueue.pop_back_val();
39124e2fe98SDimitry Andric     assert(Ptr && !isa<GlobalValue>(Ptr) &&
39224e2fe98SDimitry Andric            "Null or GlobalValue should not be inserted");
3937d523365SDimitry Andric 
394d88c1a5aSDimitry Andric     for (const Use &Us : Ptr->uses()) {
3957d523365SDimitry Andric       auto *U = dyn_cast<Instruction>(Us.getUser());
3963ca95b02SDimitry Andric       if (!U || U == LI || !DT.dominates(U, LI))
3977d523365SDimitry Andric         continue;
3987d523365SDimitry Andric 
399d88c1a5aSDimitry Andric       // Bitcast or gep with zeros are using Ptr. Add to queue to check it's
400d88c1a5aSDimitry Andric       // users.      U = bitcast Ptr
401d88c1a5aSDimitry Andric       if (isa<BitCastInst>(U)) {
40224e2fe98SDimitry Andric         LoadOperandsQueue.push_back(U);
4037d523365SDimitry Andric         continue;
4047d523365SDimitry Andric       }
40524e2fe98SDimitry Andric       // Gep with zeros is equivalent to bitcast.
40624e2fe98SDimitry Andric       // FIXME: we are not sure if some bitcast should be canonicalized to gep 0
40724e2fe98SDimitry Andric       // or gep 0 to bitcast because of SROA, so there are 2 forms. When
40824e2fe98SDimitry Andric       // typeless pointers will be ready then both cases will be gone
40924e2fe98SDimitry Andric       // (and this BFS also won't be needed).
410d88c1a5aSDimitry Andric       if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
411d88c1a5aSDimitry Andric         if (GEP->hasAllZeroIndices()) {
41224e2fe98SDimitry Andric           LoadOperandsQueue.push_back(U);
413d88c1a5aSDimitry Andric           continue;
414d88c1a5aSDimitry Andric         }
415d88c1a5aSDimitry Andric 
4167d523365SDimitry Andric       // If we hit load/store with the same invariant.group metadata (and the
4177d523365SDimitry Andric       // same pointer operand) we can assume that value pointed by pointer
4187d523365SDimitry Andric       // operand didn't change.
419f1a29dd3SDimitry Andric       if ((isa<LoadInst>(U) || isa<StoreInst>(U)) &&
4204ba319b5SDimitry Andric           U->getMetadata(LLVMContext::MD_invariant_group) != nullptr)
421f1a29dd3SDimitry Andric         ClosestDependency = GetClosestDependency(ClosestDependency, U);
4227d523365SDimitry Andric     }
4237d523365SDimitry Andric   }
424f1a29dd3SDimitry Andric 
425f1a29dd3SDimitry Andric   if (!ClosestDependency)
426d88c1a5aSDimitry Andric     return MemDepResult::getUnknown();
427f1a29dd3SDimitry Andric   if (ClosestDependency->getParent() == BB)
428f1a29dd3SDimitry Andric     return MemDepResult::getDef(ClosestDependency);
429f1a29dd3SDimitry Andric   // Def(U) can't be returned here because it is non-local. If local
430f1a29dd3SDimitry Andric   // dependency won't be found then return nonLocal counting that the
431f1a29dd3SDimitry Andric   // user will call getNonLocalPointerDependency, which will return cached
432f1a29dd3SDimitry Andric   // result.
433f1a29dd3SDimitry Andric   NonLocalDefsCache.try_emplace(
434f1a29dd3SDimitry Andric       LI, NonLocalDepResult(ClosestDependency->getParent(),
435f1a29dd3SDimitry Andric                             MemDepResult::getDef(ClosestDependency), nullptr));
4364ba319b5SDimitry Andric   ReverseNonLocalDefsCache[ClosestDependency].insert(LI);
437f1a29dd3SDimitry Andric   return MemDepResult::getNonLocal();
4387d523365SDimitry Andric }
4397d523365SDimitry Andric 
getSimplePointerDependencyFrom(const MemoryLocation & MemLoc,bool isLoad,BasicBlock::iterator ScanIt,BasicBlock * BB,Instruction * QueryInst,unsigned * Limit)4403ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
4417d523365SDimitry Andric     const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
442d88c1a5aSDimitry Andric     BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
443139f7f9bSDimitry Andric   bool isInvariantLoad = false;
44439d628a0SDimitry Andric 
445d88c1a5aSDimitry Andric   if (!Limit) {
446d88c1a5aSDimitry Andric     unsigned DefaultLimit = BlockScanLimit;
447d88c1a5aSDimitry Andric     return getSimplePointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst,
448d88c1a5aSDimitry Andric                                           &DefaultLimit);
449d88c1a5aSDimitry Andric   }
450d88c1a5aSDimitry Andric 
45139d628a0SDimitry Andric   // We must be careful with atomic accesses, as they may allow another thread
4523ca95b02SDimitry Andric   //   to touch this location, clobbering it. We are conservative: if the
45339d628a0SDimitry Andric   //   QueryInst is not a simple (non-atomic) memory access, we automatically
45439d628a0SDimitry Andric   //   return getClobber.
45539d628a0SDimitry Andric   // If it is simple, we know based on the results of
45639d628a0SDimitry Andric   // "Compiler testing via a theory of sound optimisations in the C11/C++11
45739d628a0SDimitry Andric   //   memory model" in PLDI 2013, that a non-atomic location can only be
45839d628a0SDimitry Andric   //   clobbered between a pair of a release and an acquire action, with no
45939d628a0SDimitry Andric   //   access to the location in between.
46039d628a0SDimitry Andric   // Here is an example for giving the general intuition behind this rule.
46139d628a0SDimitry Andric   // In the following code:
46239d628a0SDimitry Andric   //   store x 0;
46339d628a0SDimitry Andric   //   release action; [1]
46439d628a0SDimitry Andric   //   acquire action; [4]
46539d628a0SDimitry Andric   //   %val = load x;
46639d628a0SDimitry Andric   // It is unsafe to replace %val by 0 because another thread may be running:
46739d628a0SDimitry Andric   //   acquire action; [2]
46839d628a0SDimitry Andric   //   store x 42;
46939d628a0SDimitry Andric   //   release action; [3]
47039d628a0SDimitry Andric   // with synchronization from 1 to 2 and from 3 to 4, resulting in %val
47139d628a0SDimitry Andric   // being 42. A key property of this program however is that if either
47239d628a0SDimitry Andric   // 1 or 4 were missing, there would be a race between the store of 42
4733ca95b02SDimitry Andric   // either the store of 0 or the load (making the whole program racy).
4744d0b32cdSDimitry Andric   // The paper mentioned above shows that the same property is respected
4753ca95b02SDimitry Andric   // by every program that can detect any optimization of that kind: either
47639d628a0SDimitry Andric   // it is racy (undefined) or there is a release followed by an acquire
47739d628a0SDimitry Andric   // between the pair of accesses under consideration.
47839d628a0SDimitry Andric 
479ff0cc061SDimitry Andric   // If the load is invariant, we "know" that it doesn't alias *any* write. We
480ff0cc061SDimitry Andric   // do want to respect mustalias results since defs are useful for value
481ff0cc061SDimitry Andric   // forwarding, but any mayalias write can be assumed to be noalias.
482ff0cc061SDimitry Andric   // Arguably, this logic should be pushed inside AliasAnalysis itself.
483139f7f9bSDimitry Andric   if (isLoad && QueryInst) {
484139f7f9bSDimitry Andric     LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
48591bc56edSDimitry Andric     if (LI && LI->getMetadata(LLVMContext::MD_invariant_load) != nullptr)
486139f7f9bSDimitry Andric       isInvariantLoad = true;
487139f7f9bSDimitry Andric   }
48817a519f9SDimitry Andric 
489ff0cc061SDimitry Andric   const DataLayout &DL = BB->getModule()->getDataLayout();
490ff0cc061SDimitry Andric 
4917d523365SDimitry Andric   // Create a numbered basic block to lazily compute and cache instruction
4927d523365SDimitry Andric   // positions inside a BB. This is used to provide fast queries for relative
4937d523365SDimitry Andric   // position between two instructions in a BB and can be used by
4947d523365SDimitry Andric   // AliasAnalysis::callCapturesBefore.
4957d523365SDimitry Andric   OrderedBasicBlock OBB(BB);
4967d523365SDimitry Andric 
4973ca95b02SDimitry Andric   // Return "true" if and only if the instruction I is either a non-simple
4983ca95b02SDimitry Andric   // load or a non-simple store.
4993ca95b02SDimitry Andric   auto isNonSimpleLoadOrStore = [](Instruction *I) -> bool {
5003ca95b02SDimitry Andric     if (auto *LI = dyn_cast<LoadInst>(I))
5013ca95b02SDimitry Andric       return !LI->isSimple();
5023ca95b02SDimitry Andric     if (auto *SI = dyn_cast<StoreInst>(I))
5033ca95b02SDimitry Andric       return !SI->isSimple();
5043ca95b02SDimitry Andric     return false;
5053ca95b02SDimitry Andric   };
5063ca95b02SDimitry Andric 
5073ca95b02SDimitry Andric   // Return "true" if I is not a load and not a store, but it does access
5083ca95b02SDimitry Andric   // memory.
5093ca95b02SDimitry Andric   auto isOtherMemAccess = [](Instruction *I) -> bool {
5103ca95b02SDimitry Andric     return !isa<LoadInst>(I) && !isa<StoreInst>(I) && I->mayReadOrWriteMemory();
5113ca95b02SDimitry Andric   };
5123ca95b02SDimitry Andric 
513f22ef01cSRoman Divacky   // Walk backwards through the basic block, looking for dependencies.
514f22ef01cSRoman Divacky   while (ScanIt != BB->begin()) {
5157d523365SDimitry Andric     Instruction *Inst = &*--ScanIt;
516f785676fSDimitry Andric 
517f785676fSDimitry Andric     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
518f785676fSDimitry Andric       // Debug intrinsics don't (and can't) cause dependencies.
5193ca95b02SDimitry Andric       if (isa<DbgInfoIntrinsic>(II))
5203ca95b02SDimitry Andric         continue;
521f785676fSDimitry Andric 
52217a519f9SDimitry Andric     // Limit the amount of scanning we do so we don't end up with quadratic
52317a519f9SDimitry Andric     // running time on extreme testcases.
524d88c1a5aSDimitry Andric     --*Limit;
525d88c1a5aSDimitry Andric     if (!*Limit)
52617a519f9SDimitry Andric       return MemDepResult::getUnknown();
52717a519f9SDimitry Andric 
528f22ef01cSRoman Divacky     if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
529f22ef01cSRoman Divacky       // If we reach a lifetime begin or end marker, then the query ends here
530f22ef01cSRoman Divacky       // because the value is undefined.
5312754fe60SDimitry Andric       if (II->getIntrinsicID() == Intrinsic::lifetime_start) {
532f22ef01cSRoman Divacky         // FIXME: This only considers queries directly on the invariant-tagged
533f22ef01cSRoman Divacky         // pointer, not on query pointers that are indexed off of them.  It'd
5343b0f4066SDimitry Andric         // be nice to handle that at some point (the right approach is to use
5353b0f4066SDimitry Andric         // GetPointerBaseWithConstantOffset).
5363ca95b02SDimitry Andric         if (AA.isMustAlias(MemoryLocation(II->getArgOperand(1)), MemLoc))
537f22ef01cSRoman Divacky           return MemDepResult::getDef(II);
5382754fe60SDimitry Andric         continue;
539f22ef01cSRoman Divacky       }
540f22ef01cSRoman Divacky     }
541f22ef01cSRoman Divacky 
5423ca95b02SDimitry Andric     // Values depend on loads if the pointers are must aliased.  This means
5433ca95b02SDimitry Andric     // that a load depends on another must aliased load from the same value.
5443ca95b02SDimitry Andric     // One exception is atomic loads: a value can depend on an atomic load that
5453ca95b02SDimitry Andric     // it does not alias with when this atomic load indicates that another
5463ca95b02SDimitry Andric     // thread may be accessing the location.
547f22ef01cSRoman Divacky     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
548ff0cc061SDimitry Andric       // While volatile access cannot be eliminated, they do not have to clobber
549ff0cc061SDimitry Andric       // non-aliasing locations, as normal accesses, for example, can be safely
550ff0cc061SDimitry Andric       // reordered with volatile accesses.
551ff0cc061SDimitry Andric       if (LI->isVolatile()) {
552ff0cc061SDimitry Andric         if (!QueryInst)
553ff0cc061SDimitry Andric           // Original QueryInst *may* be volatile
554ff0cc061SDimitry Andric           return MemDepResult::getClobber(LI);
555ff0cc061SDimitry Andric         if (isVolatile(QueryInst))
556ff0cc061SDimitry Andric           // Ordering required if QueryInst is itself volatile
557ff0cc061SDimitry Andric           return MemDepResult::getClobber(LI);
558ff0cc061SDimitry Andric         // Otherwise, volatile doesn't imply any special ordering
559ff0cc061SDimitry Andric       }
560ff0cc061SDimitry Andric 
5616122f3e6SDimitry Andric       // Atomic loads have complications involved.
5623ca95b02SDimitry Andric       // A Monotonic (or higher) load is OK if the query inst is itself not
5633ca95b02SDimitry Andric       // atomic.
5646122f3e6SDimitry Andric       // FIXME: This is overly conservative.
5653ca95b02SDimitry Andric       if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
5663ca95b02SDimitry Andric         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
5673ca95b02SDimitry Andric             isOtherMemAccess(QueryInst))
56839d628a0SDimitry Andric           return MemDepResult::getClobber(LI);
5693ca95b02SDimitry Andric         if (LI->getOrdering() != AtomicOrdering::Monotonic)
570ff0cc061SDimitry Andric           return MemDepResult::getClobber(LI);
57139d628a0SDimitry Andric       }
57239d628a0SDimitry Andric 
5738f0fd8f6SDimitry Andric       MemoryLocation LoadLoc = MemoryLocation::get(LI);
574f22ef01cSRoman Divacky 
575f22ef01cSRoman Divacky       // If we found a pointer, check if it could be the same as our pointer.
5763ca95b02SDimitry Andric       AliasResult R = AA.alias(LoadLoc, MemLoc);
5773b0f4066SDimitry Andric 
5783b0f4066SDimitry Andric       if (isLoad) {
579d88c1a5aSDimitry Andric         if (R == NoAlias)
5803b0f4066SDimitry Andric           continue;
5813b0f4066SDimitry Andric 
5823b0f4066SDimitry Andric         // Must aliased loads are defs of each other.
5833dac3a9bSDimitry Andric         if (R == MustAlias)
5843b0f4066SDimitry Andric           return MemDepResult::getDef(Inst);
5853b0f4066SDimitry Andric 
586bd5abe19SDimitry Andric #if 0 // FIXME: Temporarily disabled. GVN is cleverly rewriting loads
587bd5abe19SDimitry Andric       // in terms of clobbering loads, but since it does this by looking
588bd5abe19SDimitry Andric       // at the clobbering load directly, it doesn't know about any
589bd5abe19SDimitry Andric       // phi translation that may have happened along the way.
590bd5abe19SDimitry Andric 
5913b0f4066SDimitry Andric         // If we have a partial alias, then return this as a clobber for the
5923b0f4066SDimitry Andric         // client to handle.
5933dac3a9bSDimitry Andric         if (R == PartialAlias)
5943b0f4066SDimitry Andric           return MemDepResult::getClobber(Inst);
595bd5abe19SDimitry Andric #endif
5963b0f4066SDimitry Andric 
5973b0f4066SDimitry Andric         // Random may-alias loads don't depend on each other without a
5983b0f4066SDimitry Andric         // dependence.
5993b0f4066SDimitry Andric         continue;
6003b0f4066SDimitry Andric       }
6013b0f4066SDimitry Andric 
6023b0f4066SDimitry Andric       // Stores don't depend on other no-aliased accesses.
6033dac3a9bSDimitry Andric       if (R == NoAlias)
604f22ef01cSRoman Divacky         continue;
605f22ef01cSRoman Divacky 
6062754fe60SDimitry Andric       // Stores don't alias loads from read-only memory.
6073ca95b02SDimitry Andric       if (AA.pointsToConstantMemory(LoadLoc))
6082754fe60SDimitry Andric         continue;
6092754fe60SDimitry Andric 
6103b0f4066SDimitry Andric       // Stores depend on may/must aliased loads.
611f22ef01cSRoman Divacky       return MemDepResult::getDef(Inst);
612f22ef01cSRoman Divacky     }
613f22ef01cSRoman Divacky 
614f22ef01cSRoman Divacky     if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
6156122f3e6SDimitry Andric       // Atomic stores have complications involved.
61639d628a0SDimitry Andric       // A Monotonic store is OK if the query inst is itself not atomic.
6176122f3e6SDimitry Andric       // FIXME: This is overly conservative.
6183ca95b02SDimitry Andric       if (!SI->isUnordered() && SI->isAtomic()) {
6193ca95b02SDimitry Andric         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
6203ca95b02SDimitry Andric             isOtherMemAccess(QueryInst))
62139d628a0SDimitry Andric           return MemDepResult::getClobber(SI);
6223ca95b02SDimitry Andric         if (SI->getOrdering() != AtomicOrdering::Monotonic)
623ff0cc061SDimitry Andric           return MemDepResult::getClobber(SI);
62439d628a0SDimitry Andric       }
62539d628a0SDimitry Andric 
62639d628a0SDimitry Andric       // FIXME: this is overly conservative.
62739d628a0SDimitry Andric       // While volatile access cannot be eliminated, they do not have to clobber
62839d628a0SDimitry Andric       // non-aliasing locations, as normal accesses can for example be reordered
62939d628a0SDimitry Andric       // with volatile accesses.
63039d628a0SDimitry Andric       if (SI->isVolatile())
6313ca95b02SDimitry Andric         if (!QueryInst || isNonSimpleLoadOrStore(QueryInst) ||
6323ca95b02SDimitry Andric             isOtherMemAccess(QueryInst))
6336122f3e6SDimitry Andric           return MemDepResult::getClobber(SI);
6346122f3e6SDimitry Andric 
635f22ef01cSRoman Divacky       // If alias analysis can tell that this store is guaranteed to not modify
636f22ef01cSRoman Divacky       // the query pointer, ignore it.  Use getModRefInfo to handle cases where
637f22ef01cSRoman Divacky       // the query pointer points to constant memory etc.
6382cab237bSDimitry Andric       if (!isModOrRefSet(AA.getModRefInfo(SI, MemLoc)))
639f22ef01cSRoman Divacky         continue;
640f22ef01cSRoman Divacky 
641f22ef01cSRoman Divacky       // Ok, this store might clobber the query pointer.  Check to see if it is
642f22ef01cSRoman Divacky       // a must alias: in this case, we want to return this as a def.
643da09e106SDimitry Andric       // FIXME: Use ModRefInfo::Must bit from getModRefInfo call above.
6448f0fd8f6SDimitry Andric       MemoryLocation StoreLoc = MemoryLocation::get(SI);
645f22ef01cSRoman Divacky 
646f22ef01cSRoman Divacky       // If we found a pointer, check if it could be the same as our pointer.
6473ca95b02SDimitry Andric       AliasResult R = AA.alias(StoreLoc, MemLoc);
648f22ef01cSRoman Divacky 
6493dac3a9bSDimitry Andric       if (R == NoAlias)
650f22ef01cSRoman Divacky         continue;
6513dac3a9bSDimitry Andric       if (R == MustAlias)
652f22ef01cSRoman Divacky         return MemDepResult::getDef(Inst);
653139f7f9bSDimitry Andric       if (isInvariantLoad)
654139f7f9bSDimitry Andric         continue;
6552754fe60SDimitry Andric       return MemDepResult::getClobber(Inst);
656f22ef01cSRoman Divacky     }
657f22ef01cSRoman Divacky 
658f22ef01cSRoman Divacky     // If this is an allocation, and if we know that the accessed pointer is to
659f22ef01cSRoman Divacky     // the allocation, return Def.  This means that there is no dependence and
660f22ef01cSRoman Divacky     // the access can be optimized based on that.  For example, a load could
6613ca95b02SDimitry Andric     // turn into undef.  Note that we can bypass the allocation itself when
6623ca95b02SDimitry Andric     // looking for a clobber in many cases; that's an alias property and is
6633ca95b02SDimitry Andric     // handled by BasicAA.
6643ca95b02SDimitry Andric     if (isa<AllocaInst>(Inst) || isNoAliasFn(Inst, &TLI)) {
66591bc56edSDimitry Andric       const Value *AccessPtr = GetUnderlyingObject(MemLoc.Ptr, DL);
6663ca95b02SDimitry Andric       if (AccessPtr == Inst || AA.isMustAlias(Inst, AccessPtr))
667f22ef01cSRoman Divacky         return MemDepResult::getDef(Inst);
668f22ef01cSRoman Divacky     }
669f22ef01cSRoman Divacky 
670ff0cc061SDimitry Andric     if (isInvariantLoad)
671ff0cc061SDimitry Andric       continue;
672ff0cc061SDimitry Andric 
6733ca95b02SDimitry Andric     // A release fence requires that all stores complete before it, but does
6743ca95b02SDimitry Andric     // not prevent the reordering of following loads or stores 'before' the
6753ca95b02SDimitry Andric     // fence.  As a result, we look past it when finding a dependency for
6763ca95b02SDimitry Andric     // loads.  DSE uses this to find preceeding stores to delete and thus we
6773ca95b02SDimitry Andric     // can't bypass the fence if the query instruction is a store.
6783ca95b02SDimitry Andric     if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
6793ca95b02SDimitry Andric       if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
6803ca95b02SDimitry Andric         continue;
6813ca95b02SDimitry Andric 
682f22ef01cSRoman Divacky     // See if this instruction (e.g. a call or vaarg) mod/ref's the pointer.
6833ca95b02SDimitry Andric     ModRefInfo MR = AA.getModRefInfo(Inst, MemLoc);
6847ae0e2c9SDimitry Andric     // If necessary, perform additional analysis.
6852cab237bSDimitry Andric     if (isModAndRefSet(MR))
6863ca95b02SDimitry Andric       MR = AA.callCapturesBefore(Inst, MemLoc, &DT, &OBB);
687da09e106SDimitry Andric     switch (clearMust(MR)) {
6882cab237bSDimitry Andric     case ModRefInfo::NoModRef:
689f22ef01cSRoman Divacky       // If the call has no effect on the queried pointer, just ignore it.
690f22ef01cSRoman Divacky       continue;
6912cab237bSDimitry Andric     case ModRefInfo::Mod:
692f22ef01cSRoman Divacky       return MemDepResult::getClobber(Inst);
6932cab237bSDimitry Andric     case ModRefInfo::Ref:
694f22ef01cSRoman Divacky       // If the call is known to never store to the pointer, and if this is a
695f22ef01cSRoman Divacky       // load query, we can safely ignore it (scan past it).
696f22ef01cSRoman Divacky       if (isLoad)
697f22ef01cSRoman Divacky         continue;
698f9448bf3SDimitry Andric       LLVM_FALLTHROUGH;
699f22ef01cSRoman Divacky     default:
700f22ef01cSRoman Divacky       // Otherwise, there is a potential dependence.  Return a clobber.
701f22ef01cSRoman Divacky       return MemDepResult::getClobber(Inst);
702f22ef01cSRoman Divacky     }
703f22ef01cSRoman Divacky   }
704f22ef01cSRoman Divacky 
70517a519f9SDimitry Andric   // No dependence found.  If this is the entry block of the function, it is
70617a519f9SDimitry Andric   // unknown, otherwise it is non-local.
707f22ef01cSRoman Divacky   if (BB != &BB->getParent()->getEntryBlock())
708f22ef01cSRoman Divacky     return MemDepResult::getNonLocal();
7096122f3e6SDimitry Andric   return MemDepResult::getNonFuncLocal();
710f22ef01cSRoman Divacky }
711f22ef01cSRoman Divacky 
getDependency(Instruction * QueryInst)7123ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
713f22ef01cSRoman Divacky   Instruction *ScanPos = QueryInst;
714f22ef01cSRoman Divacky 
715f22ef01cSRoman Divacky   // Check for a cached result
716f22ef01cSRoman Divacky   MemDepResult &LocalCache = LocalDeps[QueryInst];
717f22ef01cSRoman Divacky 
718f22ef01cSRoman Divacky   // If the cached entry is non-dirty, just return it.  Note that this depends
719f22ef01cSRoman Divacky   // on MemDepResult's default constructing to 'dirty'.
720f22ef01cSRoman Divacky   if (!LocalCache.isDirty())
721f22ef01cSRoman Divacky     return LocalCache;
722f22ef01cSRoman Divacky 
723f22ef01cSRoman Divacky   // Otherwise, if we have a dirty entry, we know we can start the scan at that
724f22ef01cSRoman Divacky   // instruction, which may save us some work.
725f22ef01cSRoman Divacky   if (Instruction *Inst = LocalCache.getInst()) {
726f22ef01cSRoman Divacky     ScanPos = Inst;
727f22ef01cSRoman Divacky 
728f22ef01cSRoman Divacky     RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
729f22ef01cSRoman Divacky   }
730f22ef01cSRoman Divacky 
731f22ef01cSRoman Divacky   BasicBlock *QueryParent = QueryInst->getParent();
732f22ef01cSRoman Divacky 
733f22ef01cSRoman Divacky   // Do the scan.
734f22ef01cSRoman Divacky   if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
73517a519f9SDimitry Andric     // No dependence found. If this is the entry block of the function, it is
73617a519f9SDimitry Andric     // unknown, otherwise it is non-local.
737f22ef01cSRoman Divacky     if (QueryParent != &QueryParent->getParent()->getEntryBlock())
738f22ef01cSRoman Divacky       LocalCache = MemDepResult::getNonLocal();
739f22ef01cSRoman Divacky     else
7406122f3e6SDimitry Andric       LocalCache = MemDepResult::getNonFuncLocal();
7412754fe60SDimitry Andric   } else {
7428f0fd8f6SDimitry Andric     MemoryLocation MemLoc;
7433ca95b02SDimitry Andric     ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
7442754fe60SDimitry Andric     if (MemLoc.Ptr) {
7452754fe60SDimitry Andric       // If we can do a pointer scan, make it happen.
7462cab237bSDimitry Andric       bool isLoad = !isModSet(MR);
747d88c1a5aSDimitry Andric       if (auto *II = dyn_cast<IntrinsicInst>(QueryInst))
748bd5abe19SDimitry Andric         isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
749f22ef01cSRoman Divacky 
7507d523365SDimitry Andric       LocalCache = getPointerDependencyFrom(
7517d523365SDimitry Andric           MemLoc, isLoad, ScanPos->getIterator(), QueryParent, QueryInst);
752*b5893f02SDimitry Andric     } else if (auto *QueryCall = dyn_cast<CallBase>(QueryInst)) {
753*b5893f02SDimitry Andric       bool isReadOnly = AA.onlyReadsMemory(QueryCall);
754*b5893f02SDimitry Andric       LocalCache = getCallDependencyFrom(QueryCall, isReadOnly,
755*b5893f02SDimitry Andric                                          ScanPos->getIterator(), QueryParent);
7562754fe60SDimitry Andric     } else
757f22ef01cSRoman Divacky       // Non-memory instruction.
75817a519f9SDimitry Andric       LocalCache = MemDepResult::getUnknown();
759f22ef01cSRoman Divacky   }
760f22ef01cSRoman Divacky 
761f22ef01cSRoman Divacky   // Remember the result!
762f22ef01cSRoman Divacky   if (Instruction *I = LocalCache.getInst())
763f22ef01cSRoman Divacky     ReverseLocalDeps[I].insert(QueryInst);
764f22ef01cSRoman Divacky 
765f22ef01cSRoman Divacky   return LocalCache;
766f22ef01cSRoman Divacky }
767f22ef01cSRoman Divacky 
768f22ef01cSRoman Divacky #ifndef NDEBUG
7693ca95b02SDimitry Andric /// This method is used when -debug is specified to verify that cache arrays
7703ca95b02SDimitry Andric /// are properly kept sorted.
AssertSorted(MemoryDependenceResults::NonLocalDepInfo & Cache,int Count=-1)7713ca95b02SDimitry Andric static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
772f22ef01cSRoman Divacky                          int Count = -1) {
7733ca95b02SDimitry Andric   if (Count == -1)
7743ca95b02SDimitry Andric     Count = Cache.size();
7754d0b32cdSDimitry Andric   assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
7764d0b32cdSDimitry Andric          "Cache isn't sorted!");
777f22ef01cSRoman Divacky }
778f22ef01cSRoman Divacky #endif
779f22ef01cSRoman Divacky 
7803ca95b02SDimitry Andric const MemoryDependenceResults::NonLocalDepInfo &
getNonLocalCallDependency(CallBase * QueryCall)781*b5893f02SDimitry Andric MemoryDependenceResults::getNonLocalCallDependency(CallBase *QueryCall) {
782*b5893f02SDimitry Andric   assert(getDependency(QueryCall).isNonLocal() &&
7833ca95b02SDimitry Andric          "getNonLocalCallDependency should only be used on calls with "
7843ca95b02SDimitry Andric          "non-local deps!");
785*b5893f02SDimitry Andric   PerInstNLInfo &CacheP = NonLocalDeps[QueryCall];
786f22ef01cSRoman Divacky   NonLocalDepInfo &Cache = CacheP.first;
787f22ef01cSRoman Divacky 
7883ca95b02SDimitry Andric   // This is the set of blocks that need to be recomputed.  In the cached case,
7893ca95b02SDimitry Andric   // this can happen due to instructions being deleted etc. In the uncached
7903ca95b02SDimitry Andric   // case, this starts out as the set of predecessors we care about.
791f22ef01cSRoman Divacky   SmallVector<BasicBlock *, 32> DirtyBlocks;
792f22ef01cSRoman Divacky 
793f22ef01cSRoman Divacky   if (!Cache.empty()) {
794f22ef01cSRoman Divacky     // Okay, we have a cache entry.  If we know it is not dirty, just return it
795f22ef01cSRoman Divacky     // with no computation.
796f22ef01cSRoman Divacky     if (!CacheP.second) {
797ffd1746dSEd Schouten       ++NumCacheNonLocal;
798f22ef01cSRoman Divacky       return Cache;
799f22ef01cSRoman Divacky     }
800f22ef01cSRoman Divacky 
801f22ef01cSRoman Divacky     // If we already have a partially computed set of results, scan them to
802f22ef01cSRoman Divacky     // determine what is dirty, seeding our initial DirtyBlocks worklist.
8033ca95b02SDimitry Andric     for (auto &Entry : Cache)
8043ca95b02SDimitry Andric       if (Entry.getResult().isDirty())
8053ca95b02SDimitry Andric         DirtyBlocks.push_back(Entry.getBB());
806f22ef01cSRoman Divacky 
807f22ef01cSRoman Divacky     // Sort the cache so that we can do fast binary search lookups below.
808*b5893f02SDimitry Andric     llvm::sort(Cache);
809f22ef01cSRoman Divacky 
810f22ef01cSRoman Divacky     ++NumCacheDirtyNonLocal;
811f22ef01cSRoman Divacky     // cerr << "CACHED CASE: " << DirtyBlocks.size() << " dirty: "
812f22ef01cSRoman Divacky     //     << Cache.size() << " cached: " << *QueryInst;
813f22ef01cSRoman Divacky   } else {
814f22ef01cSRoman Divacky     // Seed DirtyBlocks with each of the preds of QueryInst's block.
815*b5893f02SDimitry Andric     BasicBlock *QueryBB = QueryCall->getParent();
816ff0cc061SDimitry Andric     for (BasicBlock *Pred : PredCache.get(QueryBB))
817ff0cc061SDimitry Andric       DirtyBlocks.push_back(Pred);
818ffd1746dSEd Schouten     ++NumUncacheNonLocal;
819f22ef01cSRoman Divacky   }
820f22ef01cSRoman Divacky 
821f22ef01cSRoman Divacky   // isReadonlyCall - If this is a read-only call, we can be more aggressive.
822*b5893f02SDimitry Andric   bool isReadonlyCall = AA.onlyReadsMemory(QueryCall);
823f22ef01cSRoman Divacky 
8243ca95b02SDimitry Andric   SmallPtrSet<BasicBlock *, 32> Visited;
825f22ef01cSRoman Divacky 
826f22ef01cSRoman Divacky   unsigned NumSortedEntries = Cache.size();
8274ba319b5SDimitry Andric   LLVM_DEBUG(AssertSorted(Cache));
828f22ef01cSRoman Divacky 
829f22ef01cSRoman Divacky   // Iterate while we still have blocks to update.
830f22ef01cSRoman Divacky   while (!DirtyBlocks.empty()) {
831f22ef01cSRoman Divacky     BasicBlock *DirtyBB = DirtyBlocks.back();
832f22ef01cSRoman Divacky     DirtyBlocks.pop_back();
833f22ef01cSRoman Divacky 
834f22ef01cSRoman Divacky     // Already processed this block?
83539d628a0SDimitry Andric     if (!Visited.insert(DirtyBB).second)
836f22ef01cSRoman Divacky       continue;
837f22ef01cSRoman Divacky 
838f22ef01cSRoman Divacky     // Do a binary search to see if we already have an entry for this block in
839f22ef01cSRoman Divacky     // the cache set.  If so, find it.
8404ba319b5SDimitry Andric     LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries));
841f22ef01cSRoman Divacky     NonLocalDepInfo::iterator Entry =
842f22ef01cSRoman Divacky         std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
843f22ef01cSRoman Divacky                          NonLocalDepEntry(DirtyBB));
84491bc56edSDimitry Andric     if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
845f22ef01cSRoman Divacky       --Entry;
846f22ef01cSRoman Divacky 
84791bc56edSDimitry Andric     NonLocalDepEntry *ExistingResult = nullptr;
848f22ef01cSRoman Divacky     if (Entry != Cache.begin() + NumSortedEntries &&
849f22ef01cSRoman Divacky         Entry->getBB() == DirtyBB) {
850f22ef01cSRoman Divacky       // If we already have an entry, and if it isn't already dirty, the block
851f22ef01cSRoman Divacky       // is done.
852f22ef01cSRoman Divacky       if (!Entry->getResult().isDirty())
853f22ef01cSRoman Divacky         continue;
854f22ef01cSRoman Divacky 
855f22ef01cSRoman Divacky       // Otherwise, remember this slot so we can update the value.
856f22ef01cSRoman Divacky       ExistingResult = &*Entry;
857f22ef01cSRoman Divacky     }
858f22ef01cSRoman Divacky 
859f22ef01cSRoman Divacky     // If the dirty entry has a pointer, start scanning from it so we don't have
860f22ef01cSRoman Divacky     // to rescan the entire block.
861f22ef01cSRoman Divacky     BasicBlock::iterator ScanPos = DirtyBB->end();
862f22ef01cSRoman Divacky     if (ExistingResult) {
863f22ef01cSRoman Divacky       if (Instruction *Inst = ExistingResult->getResult().getInst()) {
8647d523365SDimitry Andric         ScanPos = Inst->getIterator();
865f22ef01cSRoman Divacky         // We're removing QueryInst's use of Inst.
866*b5893f02SDimitry Andric         RemoveFromReverseMap<Instruction *>(ReverseNonLocalDeps, Inst,
867*b5893f02SDimitry Andric                                             QueryCall);
868f22ef01cSRoman Divacky       }
869f22ef01cSRoman Divacky     }
870f22ef01cSRoman Divacky 
871f22ef01cSRoman Divacky     // Find out if this block has a local dependency for QueryInst.
872f22ef01cSRoman Divacky     MemDepResult Dep;
873f22ef01cSRoman Divacky 
874f22ef01cSRoman Divacky     if (ScanPos != DirtyBB->begin()) {
875*b5893f02SDimitry Andric       Dep = getCallDependencyFrom(QueryCall, isReadonlyCall, ScanPos, DirtyBB);
876f22ef01cSRoman Divacky     } else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
877f22ef01cSRoman Divacky       // No dependence found.  If this is the entry block of the function, it is
87817a519f9SDimitry Andric       // a clobber, otherwise it is unknown.
879f22ef01cSRoman Divacky       Dep = MemDepResult::getNonLocal();
880f22ef01cSRoman Divacky     } else {
8816122f3e6SDimitry Andric       Dep = MemDepResult::getNonFuncLocal();
882f22ef01cSRoman Divacky     }
883f22ef01cSRoman Divacky 
884f22ef01cSRoman Divacky     // If we had a dirty entry for the block, update it.  Otherwise, just add
885f22ef01cSRoman Divacky     // a new entry.
886f22ef01cSRoman Divacky     if (ExistingResult)
887f22ef01cSRoman Divacky       ExistingResult->setResult(Dep);
888f22ef01cSRoman Divacky     else
889f22ef01cSRoman Divacky       Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
890f22ef01cSRoman Divacky 
891f22ef01cSRoman Divacky     // If the block has a dependency (i.e. it isn't completely transparent to
892f22ef01cSRoman Divacky     // the value), remember the association!
893f22ef01cSRoman Divacky     if (!Dep.isNonLocal()) {
894f22ef01cSRoman Divacky       // Keep the ReverseNonLocalDeps map up to date so we can efficiently
895f22ef01cSRoman Divacky       // update this when we remove instructions.
896f22ef01cSRoman Divacky       if (Instruction *Inst = Dep.getInst())
897*b5893f02SDimitry Andric         ReverseNonLocalDeps[Inst].insert(QueryCall);
898f22ef01cSRoman Divacky     } else {
899f22ef01cSRoman Divacky 
900f22ef01cSRoman Divacky       // If the block *is* completely transparent to the load, we need to check
901f22ef01cSRoman Divacky       // the predecessors of this block.  Add them to our worklist.
902ff0cc061SDimitry Andric       for (BasicBlock *Pred : PredCache.get(DirtyBB))
903ff0cc061SDimitry Andric         DirtyBlocks.push_back(Pred);
904f22ef01cSRoman Divacky     }
905f22ef01cSRoman Divacky   }
906f22ef01cSRoman Divacky 
907f22ef01cSRoman Divacky   return Cache;
908f22ef01cSRoman Divacky }
909f22ef01cSRoman Divacky 
getNonLocalPointerDependency(Instruction * QueryInst,SmallVectorImpl<NonLocalDepResult> & Result)9103ca95b02SDimitry Andric void MemoryDependenceResults::getNonLocalPointerDependency(
9113ca95b02SDimitry Andric     Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
9128f0fd8f6SDimitry Andric   const MemoryLocation Loc = MemoryLocation::get(QueryInst);
91339d628a0SDimitry Andric   bool isLoad = isa<LoadInst>(QueryInst);
91439d628a0SDimitry Andric   BasicBlock *FromBB = QueryInst->getParent();
91539d628a0SDimitry Andric   assert(FromBB);
91639d628a0SDimitry Andric 
9172754fe60SDimitry Andric   assert(Loc.Ptr->getType()->isPointerTy() &&
918f22ef01cSRoman Divacky          "Can't get pointer deps of a non-pointer!");
919f22ef01cSRoman Divacky   Result.clear();
920f1a29dd3SDimitry Andric   {
9214ba319b5SDimitry Andric     // Check if there is cached Def with invariant.group.
922f1a29dd3SDimitry Andric     auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst);
923f1a29dd3SDimitry Andric     if (NonLocalDefIt != NonLocalDefsCache.end()) {
9244ba319b5SDimitry Andric       Result.push_back(NonLocalDefIt->second);
9254ba319b5SDimitry Andric       ReverseNonLocalDefsCache[NonLocalDefIt->second.getResult().getInst()]
9264ba319b5SDimitry Andric           .erase(QueryInst);
927f1a29dd3SDimitry Andric       NonLocalDefsCache.erase(NonLocalDefIt);
928f1a29dd3SDimitry Andric       return;
929f1a29dd3SDimitry Andric     }
930f1a29dd3SDimitry Andric   }
93139d628a0SDimitry Andric   // This routine does not expect to deal with volatile instructions.
93239d628a0SDimitry Andric   // Doing so would require piping through the QueryInst all the way through.
93339d628a0SDimitry Andric   // TODO: volatiles can't be elided, but they can be reordered with other
93439d628a0SDimitry Andric   // non-volatile accesses.
935ff0cc061SDimitry Andric 
93639d628a0SDimitry Andric   // We currently give up on any instruction which is ordered, but we do handle
93739d628a0SDimitry Andric   // atomic instructions which are unordered.
93839d628a0SDimitry Andric   // TODO: Handle ordered instructions
93939d628a0SDimitry Andric   auto isOrdered = [](Instruction *Inst) {
94039d628a0SDimitry Andric     if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
94139d628a0SDimitry Andric       return !LI->isUnordered();
94239d628a0SDimitry Andric     } else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
94339d628a0SDimitry Andric       return !SI->isUnordered();
94439d628a0SDimitry Andric     }
94539d628a0SDimitry Andric     return false;
94639d628a0SDimitry Andric   };
94739d628a0SDimitry Andric   if (isVolatile(QueryInst) || isOrdered(QueryInst)) {
9483ca95b02SDimitry Andric     Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
94939d628a0SDimitry Andric                                        const_cast<Value *>(Loc.Ptr)));
95039d628a0SDimitry Andric     return;
95139d628a0SDimitry Andric   }
952ff0cc061SDimitry Andric   const DataLayout &DL = FromBB->getModule()->getDataLayout();
9533ca95b02SDimitry Andric   PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
954f22ef01cSRoman Divacky 
955f22ef01cSRoman Divacky   // This is the set of blocks we've inspected, and the pointer we consider in
956f22ef01cSRoman Divacky   // each block.  Because of critical edges, we currently bail out if querying
957f22ef01cSRoman Divacky   // a block with multiple different pointers.  This can happen during PHI
958f22ef01cSRoman Divacky   // translation.
959f22ef01cSRoman Divacky   DenseMap<BasicBlock *, Value *> Visited;
9603ca95b02SDimitry Andric   if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
961f22ef01cSRoman Divacky                                    Result, Visited, true))
962f22ef01cSRoman Divacky     return;
963f22ef01cSRoman Divacky   Result.clear();
9643ca95b02SDimitry Andric   Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
9652754fe60SDimitry Andric                                      const_cast<Value *>(Loc.Ptr)));
966f22ef01cSRoman Divacky }
967f22ef01cSRoman Divacky 
9683ca95b02SDimitry Andric /// Compute the memdep value for BB with Pointer/PointeeSize using either
9693ca95b02SDimitry Andric /// cached information in Cache or by doing a lookup (which may use dirty cache
9703ca95b02SDimitry Andric /// info if available).
9713ca95b02SDimitry Andric ///
9723ca95b02SDimitry Andric /// If we do a lookup, add the result to the cache.
GetNonLocalInfoForBlock(Instruction * QueryInst,const MemoryLocation & Loc,bool isLoad,BasicBlock * BB,NonLocalDepInfo * Cache,unsigned NumSortedEntries)9733ca95b02SDimitry Andric MemDepResult MemoryDependenceResults::GetNonLocalInfoForBlock(
9748f0fd8f6SDimitry Andric     Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
9758f0fd8f6SDimitry Andric     BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries) {
976f22ef01cSRoman Divacky 
977f22ef01cSRoman Divacky   // Do a binary search to see if we already have an entry for this block in
978f22ef01cSRoman Divacky   // the cache set.  If so, find it.
9793ca95b02SDimitry Andric   NonLocalDepInfo::iterator Entry = std::upper_bound(
9803ca95b02SDimitry Andric       Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
981f22ef01cSRoman Divacky   if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
982f22ef01cSRoman Divacky     --Entry;
983f22ef01cSRoman Divacky 
98491bc56edSDimitry Andric   NonLocalDepEntry *ExistingResult = nullptr;
985f22ef01cSRoman Divacky   if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
986f22ef01cSRoman Divacky     ExistingResult = &*Entry;
987f22ef01cSRoman Divacky 
988f22ef01cSRoman Divacky   // If we have a cached entry, and it is non-dirty, use it as the value for
989f22ef01cSRoman Divacky   // this dependency.
990f22ef01cSRoman Divacky   if (ExistingResult && !ExistingResult->getResult().isDirty()) {
991f22ef01cSRoman Divacky     ++NumCacheNonLocalPtr;
992f22ef01cSRoman Divacky     return ExistingResult->getResult();
993f22ef01cSRoman Divacky   }
994f22ef01cSRoman Divacky 
995f22ef01cSRoman Divacky   // Otherwise, we have to scan for the value.  If we have a dirty cache
996f22ef01cSRoman Divacky   // entry, start scanning from its position, otherwise we scan from the end
997f22ef01cSRoman Divacky   // of the block.
998f22ef01cSRoman Divacky   BasicBlock::iterator ScanPos = BB->end();
999f22ef01cSRoman Divacky   if (ExistingResult && ExistingResult->getResult().getInst()) {
1000f22ef01cSRoman Divacky     assert(ExistingResult->getResult().getInst()->getParent() == BB &&
1001f22ef01cSRoman Divacky            "Instruction invalidated?");
1002f22ef01cSRoman Divacky     ++NumCacheDirtyNonLocalPtr;
10037d523365SDimitry Andric     ScanPos = ExistingResult->getResult().getInst()->getIterator();
1004f22ef01cSRoman Divacky 
1005f22ef01cSRoman Divacky     // Eliminating the dirty entry from 'Cache', so update the reverse info.
10062754fe60SDimitry Andric     ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
10077d523365SDimitry Andric     RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
1008f22ef01cSRoman Divacky   } else {
1009f22ef01cSRoman Divacky     ++NumUncacheNonLocalPtr;
1010f22ef01cSRoman Divacky   }
1011f22ef01cSRoman Divacky 
1012f22ef01cSRoman Divacky   // Scan the block for the dependency.
10133ca95b02SDimitry Andric   MemDepResult Dep =
10143ca95b02SDimitry Andric       getPointerDependencyFrom(Loc, isLoad, ScanPos, BB, QueryInst);
1015f22ef01cSRoman Divacky 
1016f22ef01cSRoman Divacky   // If we had a dirty entry for the block, update it.  Otherwise, just add
1017f22ef01cSRoman Divacky   // a new entry.
1018f22ef01cSRoman Divacky   if (ExistingResult)
1019f22ef01cSRoman Divacky     ExistingResult->setResult(Dep);
1020f22ef01cSRoman Divacky   else
1021f22ef01cSRoman Divacky     Cache->push_back(NonLocalDepEntry(BB, Dep));
1022f22ef01cSRoman Divacky 
1023f22ef01cSRoman Divacky   // If the block has a dependency (i.e. it isn't completely transparent to
1024f22ef01cSRoman Divacky   // the value), remember the reverse association because we just added it
1025f22ef01cSRoman Divacky   // to Cache!
10266122f3e6SDimitry Andric   if (!Dep.isDef() && !Dep.isClobber())
1027f22ef01cSRoman Divacky     return Dep;
1028f22ef01cSRoman Divacky 
1029f22ef01cSRoman Divacky   // Keep the ReverseNonLocalPtrDeps map up to date so we can efficiently
1030f22ef01cSRoman Divacky   // update MemDep when we remove instructions.
1031f22ef01cSRoman Divacky   Instruction *Inst = Dep.getInst();
1032f22ef01cSRoman Divacky   assert(Inst && "Didn't depend on anything?");
10332754fe60SDimitry Andric   ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
1034f22ef01cSRoman Divacky   ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
1035f22ef01cSRoman Divacky   return Dep;
1036f22ef01cSRoman Divacky }
1037f22ef01cSRoman Divacky 
10383ca95b02SDimitry Andric /// Sort the NonLocalDepInfo cache, given a certain number of elements in the
10393ca95b02SDimitry Andric /// array that are already properly ordered.
10403ca95b02SDimitry Andric ///
10413ca95b02SDimitry Andric /// This is optimized for the case when only a few entries are added.
1042f22ef01cSRoman Divacky static void
SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo & Cache,unsigned NumSortedEntries)10433ca95b02SDimitry Andric SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
1044f22ef01cSRoman Divacky                          unsigned NumSortedEntries) {
1045f22ef01cSRoman Divacky   switch (Cache.size() - NumSortedEntries) {
1046f22ef01cSRoman Divacky   case 0:
1047f22ef01cSRoman Divacky     // done, no new entries.
1048f22ef01cSRoman Divacky     break;
1049f22ef01cSRoman Divacky   case 2: {
1050f22ef01cSRoman Divacky     // Two new entries, insert the last one into place.
1051f22ef01cSRoman Divacky     NonLocalDepEntry Val = Cache.back();
1052f22ef01cSRoman Divacky     Cache.pop_back();
10533ca95b02SDimitry Andric     MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1054f22ef01cSRoman Divacky         std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
1055f22ef01cSRoman Divacky     Cache.insert(Entry, Val);
1056d88c1a5aSDimitry Andric     LLVM_FALLTHROUGH;
1057f22ef01cSRoman Divacky   }
1058f22ef01cSRoman Divacky   case 1:
1059f22ef01cSRoman Divacky     // One new entry, Just insert the new value at the appropriate position.
1060f22ef01cSRoman Divacky     if (Cache.size() != 1) {
1061f22ef01cSRoman Divacky       NonLocalDepEntry Val = Cache.back();
1062f22ef01cSRoman Divacky       Cache.pop_back();
10633ca95b02SDimitry Andric       MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
1064f22ef01cSRoman Divacky           std::upper_bound(Cache.begin(), Cache.end(), Val);
1065f22ef01cSRoman Divacky       Cache.insert(Entry, Val);
1066f22ef01cSRoman Divacky     }
1067f22ef01cSRoman Divacky     break;
1068f22ef01cSRoman Divacky   default:
1069f22ef01cSRoman Divacky     // Added many values, do a full scale sort.
1070*b5893f02SDimitry Andric     llvm::sort(Cache);
1071f22ef01cSRoman Divacky     break;
1072f22ef01cSRoman Divacky   }
1073f22ef01cSRoman Divacky }
1074f22ef01cSRoman Divacky 
10753ca95b02SDimitry Andric /// Perform a dependency query based on pointer/pointeesize starting at the end
10763ca95b02SDimitry Andric /// of StartBB.
10773ca95b02SDimitry Andric ///
10783ca95b02SDimitry Andric /// Add any clobber/def results to the results vector and keep track of which
10793ca95b02SDimitry Andric /// blocks are visited in 'Visited'.
1080f22ef01cSRoman Divacky ///
1081f22ef01cSRoman Divacky /// This has special behavior for the first block queries (when SkipFirstBlock
1082f22ef01cSRoman Divacky /// is true).  In this special case, it ignores the contents of the specified
1083f22ef01cSRoman Divacky /// block and starts returning dependence info for its predecessors.
1084f22ef01cSRoman Divacky ///
10853ca95b02SDimitry Andric /// This function returns true on success, or false to indicate that it could
1086f22ef01cSRoman Divacky /// not compute dependence information for some reason.  This should be treated
1087f22ef01cSRoman Divacky /// as a clobber dependence on the first instruction in the predecessor block.
getNonLocalPointerDepFromBB(Instruction * QueryInst,const PHITransAddr & Pointer,const MemoryLocation & Loc,bool isLoad,BasicBlock * StartBB,SmallVectorImpl<NonLocalDepResult> & Result,DenseMap<BasicBlock *,Value * > & Visited,bool SkipFirstBlock)10883ca95b02SDimitry Andric bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
10898f0fd8f6SDimitry Andric     Instruction *QueryInst, const PHITransAddr &Pointer,
10908f0fd8f6SDimitry Andric     const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
1091f22ef01cSRoman Divacky     SmallVectorImpl<NonLocalDepResult> &Result,
10928f0fd8f6SDimitry Andric     DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock) {
1093f22ef01cSRoman Divacky   // Look up the cached info for Pointer.
1094f22ef01cSRoman Divacky   ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
1095f22ef01cSRoman Divacky 
10962754fe60SDimitry Andric   // Set up a temporary NLPI value. If the map doesn't yet have an entry for
10972754fe60SDimitry Andric   // CacheKey, this value will be inserted as the associated value. Otherwise,
10982754fe60SDimitry Andric   // it'll be ignored, and we'll have to check to see if the cached size and
109939d628a0SDimitry Andric   // aa tags are consistent with the current query.
11002754fe60SDimitry Andric   NonLocalPointerInfo InitialNLPI;
11012754fe60SDimitry Andric   InitialNLPI.Size = Loc.Size;
110239d628a0SDimitry Andric   InitialNLPI.AATags = Loc.AATags;
11032754fe60SDimitry Andric 
11042754fe60SDimitry Andric   // Get the NLPI for CacheKey, inserting one into the map if it doesn't
11052754fe60SDimitry Andric   // already have one.
11062754fe60SDimitry Andric   std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
11072754fe60SDimitry Andric       NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
11082754fe60SDimitry Andric   NonLocalPointerInfo *CacheInfo = &Pair.first->second;
11092754fe60SDimitry Andric 
11102754fe60SDimitry Andric   // If we already have a cache entry for this CacheKey, we may need to do some
11112754fe60SDimitry Andric   // work to reconcile the cache entry and the current query.
11122754fe60SDimitry Andric   if (!Pair.second) {
1113*b5893f02SDimitry Andric     if (CacheInfo->Size != Loc.Size) {
1114*b5893f02SDimitry Andric       bool ThrowOutEverything;
1115*b5893f02SDimitry Andric       if (CacheInfo->Size.hasValue() && Loc.Size.hasValue()) {
1116*b5893f02SDimitry Andric         // FIXME: We may be able to do better in the face of results with mixed
1117*b5893f02SDimitry Andric         // precision. We don't appear to get them in practice, though, so just
1118*b5893f02SDimitry Andric         // be conservative.
1119*b5893f02SDimitry Andric         ThrowOutEverything =
1120*b5893f02SDimitry Andric             CacheInfo->Size.isPrecise() != Loc.Size.isPrecise() ||
1121*b5893f02SDimitry Andric             CacheInfo->Size.getValue() < Loc.Size.getValue();
1122*b5893f02SDimitry Andric       } else {
1123*b5893f02SDimitry Andric         // For our purposes, unknown size > all others.
1124*b5893f02SDimitry Andric         ThrowOutEverything = !Loc.Size.hasValue();
1125*b5893f02SDimitry Andric       }
1126*b5893f02SDimitry Andric 
1127*b5893f02SDimitry Andric       if (ThrowOutEverything) {
1128fe4fed2eSDimitry Andric         // The query's Size is greater than the cached one. Throw out the
1129fe4fed2eSDimitry Andric         // cached data and proceed with the query at the greater size.
11302754fe60SDimitry Andric         CacheInfo->Pair = BBSkipFirstBlockPair();
11312754fe60SDimitry Andric         CacheInfo->Size = Loc.Size;
11323ca95b02SDimitry Andric         for (auto &Entry : CacheInfo->NonLocalDeps)
11333ca95b02SDimitry Andric           if (Instruction *Inst = Entry.getResult().getInst())
11342754fe60SDimitry Andric             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
11352754fe60SDimitry Andric         CacheInfo->NonLocalDeps.clear();
1136*b5893f02SDimitry Andric       } else {
1137fe4fed2eSDimitry Andric         // This query's Size is less than the cached one. Conservatively restart
1138fe4fed2eSDimitry Andric         // the query using the greater size.
1139fe4fed2eSDimitry Andric         return getNonLocalPointerDepFromBB(
1140fe4fed2eSDimitry Andric             QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
1141fe4fed2eSDimitry Andric             StartBB, Result, Visited, SkipFirstBlock);
11422754fe60SDimitry Andric       }
1143*b5893f02SDimitry Andric     }
11442754fe60SDimitry Andric 
114539d628a0SDimitry Andric     // If the query's AATags are inconsistent with the cached one,
11462754fe60SDimitry Andric     // conservatively throw out the cached data and restart the query with
11472754fe60SDimitry Andric     // no tag if needed.
114839d628a0SDimitry Andric     if (CacheInfo->AATags != Loc.AATags) {
114939d628a0SDimitry Andric       if (CacheInfo->AATags) {
11502754fe60SDimitry Andric         CacheInfo->Pair = BBSkipFirstBlockPair();
115139d628a0SDimitry Andric         CacheInfo->AATags = AAMDNodes();
11523ca95b02SDimitry Andric         for (auto &Entry : CacheInfo->NonLocalDeps)
11533ca95b02SDimitry Andric           if (Instruction *Inst = Entry.getResult().getInst())
11542754fe60SDimitry Andric             RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
11552754fe60SDimitry Andric         CacheInfo->NonLocalDeps.clear();
11562754fe60SDimitry Andric       }
115739d628a0SDimitry Andric       if (Loc.AATags)
11583ca95b02SDimitry Andric         return getNonLocalPointerDepFromBB(
11593ca95b02SDimitry Andric             QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
11603ca95b02SDimitry Andric             Visited, SkipFirstBlock);
11612754fe60SDimitry Andric     }
11622754fe60SDimitry Andric   }
11632754fe60SDimitry Andric 
11642754fe60SDimitry Andric   NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
1165f22ef01cSRoman Divacky 
1166f22ef01cSRoman Divacky   // If we have valid cached information for exactly the block we are
1167f22ef01cSRoman Divacky   // investigating, just return it with no recomputation.
11682754fe60SDimitry Andric   if (CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
1169f22ef01cSRoman Divacky     // We have a fully cached result for this query then we can just return the
1170f22ef01cSRoman Divacky     // cached results and populate the visited set.  However, we have to verify
1171f22ef01cSRoman Divacky     // that we don't already have conflicting results for these blocks.  Check
1172f22ef01cSRoman Divacky     // to ensure that if a block in the results set is in the visited set that
1173f22ef01cSRoman Divacky     // it was for the same pointer query.
1174f22ef01cSRoman Divacky     if (!Visited.empty()) {
11753ca95b02SDimitry Andric       for (auto &Entry : *Cache) {
11763ca95b02SDimitry Andric         DenseMap<BasicBlock *, Value *>::iterator VI =
11773ca95b02SDimitry Andric             Visited.find(Entry.getBB());
1178f22ef01cSRoman Divacky         if (VI == Visited.end() || VI->second == Pointer.getAddr())
1179f22ef01cSRoman Divacky           continue;
1180f22ef01cSRoman Divacky 
11813ca95b02SDimitry Andric         // We have a pointer mismatch in a block.  Just return false, saying
1182f22ef01cSRoman Divacky         // that something was clobbered in this result.  We could also do a
1183f22ef01cSRoman Divacky         // non-fully cached query, but there is little point in doing this.
11843ca95b02SDimitry Andric         return false;
1185f22ef01cSRoman Divacky       }
1186f22ef01cSRoman Divacky     }
1187f22ef01cSRoman Divacky 
1188f22ef01cSRoman Divacky     Value *Addr = Pointer.getAddr();
11893ca95b02SDimitry Andric     for (auto &Entry : *Cache) {
11903ca95b02SDimitry Andric       Visited.insert(std::make_pair(Entry.getBB(), Addr));
11913ca95b02SDimitry Andric       if (Entry.getResult().isNonLocal()) {
1192284c1978SDimitry Andric         continue;
1193284c1978SDimitry Andric       }
1194284c1978SDimitry Andric 
11953ca95b02SDimitry Andric       if (DT.isReachableFromEntry(Entry.getBB())) {
11963ca95b02SDimitry Andric         Result.push_back(
11973ca95b02SDimitry Andric             NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
1198f22ef01cSRoman Divacky       }
1199284c1978SDimitry Andric     }
1200f22ef01cSRoman Divacky     ++NumCacheCompleteNonLocalPtr;
12013ca95b02SDimitry Andric     return true;
1202f22ef01cSRoman Divacky   }
1203f22ef01cSRoman Divacky 
1204f22ef01cSRoman Divacky   // Otherwise, either this is a new block, a block with an invalid cache
1205f22ef01cSRoman Divacky   // pointer or one that we're about to invalidate by putting more info into it
1206f22ef01cSRoman Divacky   // than its valid cache info.  If empty, the result will be valid cache info,
1207f22ef01cSRoman Divacky   // otherwise it isn't.
1208f22ef01cSRoman Divacky   if (Cache->empty())
12092754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
1210f22ef01cSRoman Divacky   else
12112754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair();
1212f22ef01cSRoman Divacky 
1213f22ef01cSRoman Divacky   SmallVector<BasicBlock *, 32> Worklist;
1214f22ef01cSRoman Divacky   Worklist.push_back(StartBB);
1215f22ef01cSRoman Divacky 
1216bd5abe19SDimitry Andric   // PredList used inside loop.
1217bd5abe19SDimitry Andric   SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
1218bd5abe19SDimitry Andric 
1219f22ef01cSRoman Divacky   // Keep track of the entries that we know are sorted.  Previously cached
1220f22ef01cSRoman Divacky   // entries will all be sorted.  The entries we add we only sort on demand (we
1221f22ef01cSRoman Divacky   // don't insert every element into its sorted position).  We know that we
1222f22ef01cSRoman Divacky   // won't get any reuse from currently inserted values, because we don't
1223f22ef01cSRoman Divacky   // revisit blocks after we insert info for them.
1224f22ef01cSRoman Divacky   unsigned NumSortedEntries = Cache->size();
12253ca95b02SDimitry Andric   unsigned WorklistEntries = BlockNumberLimit;
12263ca95b02SDimitry Andric   bool GotWorklistLimit = false;
12274ba319b5SDimitry Andric   LLVM_DEBUG(AssertSorted(*Cache));
1228f22ef01cSRoman Divacky 
1229f22ef01cSRoman Divacky   while (!Worklist.empty()) {
1230f22ef01cSRoman Divacky     BasicBlock *BB = Worklist.pop_back_val();
1231f22ef01cSRoman Divacky 
123239d628a0SDimitry Andric     // If we do process a large number of blocks it becomes very expensive and
123339d628a0SDimitry Andric     // likely it isn't worth worrying about
123439d628a0SDimitry Andric     if (Result.size() > NumResultsLimit) {
123539d628a0SDimitry Andric       Worklist.clear();
123639d628a0SDimitry Andric       // Sort it now (if needed) so that recursive invocations of
123739d628a0SDimitry Andric       // getNonLocalPointerDepFromBB and other routines that could reuse the
123839d628a0SDimitry Andric       // cache value will only see properly sorted cache arrays.
123939d628a0SDimitry Andric       if (Cache && NumSortedEntries != Cache->size()) {
124039d628a0SDimitry Andric         SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
124139d628a0SDimitry Andric       }
124239d628a0SDimitry Andric       // Since we bail out, the "Cache" set won't contain all of the
124339d628a0SDimitry Andric       // results for the query.  This is ok (we can still use it to accelerate
124439d628a0SDimitry Andric       // specific block queries) but we can't do the fastpath "return all
124539d628a0SDimitry Andric       // results from the set".  Clear out the indicator for this.
124639d628a0SDimitry Andric       CacheInfo->Pair = BBSkipFirstBlockPair();
12473ca95b02SDimitry Andric       return false;
124839d628a0SDimitry Andric     }
124939d628a0SDimitry Andric 
1250f22ef01cSRoman Divacky     // Skip the first block if we have it.
1251f22ef01cSRoman Divacky     if (!SkipFirstBlock) {
1252f22ef01cSRoman Divacky       // Analyze the dependency of *Pointer in FromBB.  See if we already have
1253f22ef01cSRoman Divacky       // been here.
1254f22ef01cSRoman Divacky       assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
1255f22ef01cSRoman Divacky 
1256f22ef01cSRoman Divacky       // Get the dependency info for Pointer in BB.  If we have cached
1257f22ef01cSRoman Divacky       // information, we will use it, otherwise we compute it.
12584ba319b5SDimitry Andric       LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries));
12593ca95b02SDimitry Andric       MemDepResult Dep = GetNonLocalInfoForBlock(QueryInst, Loc, isLoad, BB,
12603ca95b02SDimitry Andric                                                  Cache, NumSortedEntries);
1261f22ef01cSRoman Divacky 
1262f22ef01cSRoman Divacky       // If we got a Def or Clobber, add this to the list of results.
1263284c1978SDimitry Andric       if (!Dep.isNonLocal()) {
12643ca95b02SDimitry Andric         if (DT.isReachableFromEntry(BB)) {
1265f22ef01cSRoman Divacky           Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
1266f22ef01cSRoman Divacky           continue;
1267f22ef01cSRoman Divacky         }
1268f22ef01cSRoman Divacky       }
1269284c1978SDimitry Andric     }
1270f22ef01cSRoman Divacky 
1271f22ef01cSRoman Divacky     // If 'Pointer' is an instruction defined in this block, then we need to do
1272f22ef01cSRoman Divacky     // phi translation to change it into a value live in the predecessor block.
1273f22ef01cSRoman Divacky     // If not, we just add the predecessors to the worklist and scan them with
1274f22ef01cSRoman Divacky     // the same Pointer.
1275f22ef01cSRoman Divacky     if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
1276f22ef01cSRoman Divacky       SkipFirstBlock = false;
1277bd5abe19SDimitry Andric       SmallVector<BasicBlock *, 16> NewBlocks;
1278ff0cc061SDimitry Andric       for (BasicBlock *Pred : PredCache.get(BB)) {
1279f22ef01cSRoman Divacky         // Verify that we haven't looked at this block yet.
12803ca95b02SDimitry Andric         std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
12813ca95b02SDimitry Andric             Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
1282f22ef01cSRoman Divacky         if (InsertRes.second) {
1283f22ef01cSRoman Divacky           // First time we've looked at *PI.
1284ff0cc061SDimitry Andric           NewBlocks.push_back(Pred);
1285f22ef01cSRoman Divacky           continue;
1286f22ef01cSRoman Divacky         }
1287f22ef01cSRoman Divacky 
1288f22ef01cSRoman Divacky         // If we have seen this block before, but it was with a different
1289f22ef01cSRoman Divacky         // pointer then we have a phi translation failure and we have to treat
1290f22ef01cSRoman Divacky         // this as a clobber.
1291bd5abe19SDimitry Andric         if (InsertRes.first->second != Pointer.getAddr()) {
1292bd5abe19SDimitry Andric           // Make sure to clean up the Visited map before continuing on to
1293bd5abe19SDimitry Andric           // PredTranslationFailure.
1294bd5abe19SDimitry Andric           for (unsigned i = 0; i < NewBlocks.size(); i++)
1295bd5abe19SDimitry Andric             Visited.erase(NewBlocks[i]);
1296f22ef01cSRoman Divacky           goto PredTranslationFailure;
1297f22ef01cSRoman Divacky         }
1298bd5abe19SDimitry Andric       }
12993ca95b02SDimitry Andric       if (NewBlocks.size() > WorklistEntries) {
13003ca95b02SDimitry Andric         // Make sure to clean up the Visited map before continuing on to
13013ca95b02SDimitry Andric         // PredTranslationFailure.
13023ca95b02SDimitry Andric         for (unsigned i = 0; i < NewBlocks.size(); i++)
13033ca95b02SDimitry Andric           Visited.erase(NewBlocks[i]);
13043ca95b02SDimitry Andric         GotWorklistLimit = true;
13053ca95b02SDimitry Andric         goto PredTranslationFailure;
13063ca95b02SDimitry Andric       }
13073ca95b02SDimitry Andric       WorklistEntries -= NewBlocks.size();
1308bd5abe19SDimitry Andric       Worklist.append(NewBlocks.begin(), NewBlocks.end());
1309f22ef01cSRoman Divacky       continue;
1310f22ef01cSRoman Divacky     }
1311f22ef01cSRoman Divacky 
1312f22ef01cSRoman Divacky     // We do need to do phi translation, if we know ahead of time we can't phi
1313f22ef01cSRoman Divacky     // translate this value, don't even try.
1314f22ef01cSRoman Divacky     if (!Pointer.IsPotentiallyPHITranslatable())
1315f22ef01cSRoman Divacky       goto PredTranslationFailure;
1316f22ef01cSRoman Divacky 
1317f22ef01cSRoman Divacky     // We may have added values to the cache list before this PHI translation.
1318f22ef01cSRoman Divacky     // If so, we haven't done anything to ensure that the cache remains sorted.
1319f22ef01cSRoman Divacky     // Sort it now (if needed) so that recursive invocations of
1320f22ef01cSRoman Divacky     // getNonLocalPointerDepFromBB and other routines that could reuse the cache
1321f22ef01cSRoman Divacky     // value will only see properly sorted cache arrays.
1322f22ef01cSRoman Divacky     if (Cache && NumSortedEntries != Cache->size()) {
1323f22ef01cSRoman Divacky       SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
1324f22ef01cSRoman Divacky       NumSortedEntries = Cache->size();
1325f22ef01cSRoman Divacky     }
132691bc56edSDimitry Andric     Cache = nullptr;
1327f22ef01cSRoman Divacky 
1328bd5abe19SDimitry Andric     PredList.clear();
1329ff0cc061SDimitry Andric     for (BasicBlock *Pred : PredCache.get(BB)) {
1330bd5abe19SDimitry Andric       PredList.push_back(std::make_pair(Pred, Pointer));
1331f22ef01cSRoman Divacky 
1332f22ef01cSRoman Divacky       // Get the PHI translated pointer in this predecessor.  This can fail if
1333f22ef01cSRoman Divacky       // not translatable, in which case the getAddr() returns null.
1334bd5abe19SDimitry Andric       PHITransAddr &PredPointer = PredList.back().second;
13353ca95b02SDimitry Andric       PredPointer.PHITranslateValue(BB, Pred, &DT, /*MustDominate=*/false);
1336f22ef01cSRoman Divacky       Value *PredPtrVal = PredPointer.getAddr();
1337f22ef01cSRoman Divacky 
1338f22ef01cSRoman Divacky       // Check to see if we have already visited this pred block with another
1339f22ef01cSRoman Divacky       // pointer.  If so, we can't do this lookup.  This failure can occur
1340f22ef01cSRoman Divacky       // with PHI translation when a critical edge exists and the PHI node in
1341f22ef01cSRoman Divacky       // the successor translates to a pointer value different than the
1342f22ef01cSRoman Divacky       // pointer the block was first analyzed with.
13433ca95b02SDimitry Andric       std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
13443ca95b02SDimitry Andric           Visited.insert(std::make_pair(Pred, PredPtrVal));
1345f22ef01cSRoman Divacky 
1346f22ef01cSRoman Divacky       if (!InsertRes.second) {
1347bd5abe19SDimitry Andric         // We found the pred; take it off the list of preds to visit.
1348bd5abe19SDimitry Andric         PredList.pop_back();
1349bd5abe19SDimitry Andric 
1350f22ef01cSRoman Divacky         // If the predecessor was visited with PredPtr, then we already did
1351f22ef01cSRoman Divacky         // the analysis and can ignore it.
1352f22ef01cSRoman Divacky         if (InsertRes.first->second == PredPtrVal)
1353f22ef01cSRoman Divacky           continue;
1354f22ef01cSRoman Divacky 
1355f22ef01cSRoman Divacky         // Otherwise, the block was previously analyzed with a different
1356f22ef01cSRoman Divacky         // pointer.  We can't represent the result of this case, so we just
1357f22ef01cSRoman Divacky         // treat this as a phi translation failure.
1358bd5abe19SDimitry Andric 
1359bd5abe19SDimitry Andric         // Make sure to clean up the Visited map before continuing on to
1360bd5abe19SDimitry Andric         // PredTranslationFailure.
1361139f7f9bSDimitry Andric         for (unsigned i = 0, n = PredList.size(); i < n; ++i)
1362bd5abe19SDimitry Andric           Visited.erase(PredList[i].first);
1363bd5abe19SDimitry Andric 
1364f22ef01cSRoman Divacky         goto PredTranslationFailure;
1365f22ef01cSRoman Divacky       }
1366bd5abe19SDimitry Andric     }
1367f22ef01cSRoman Divacky 
1368bd5abe19SDimitry Andric     // Actually process results here; this need to be a separate loop to avoid
1369bd5abe19SDimitry Andric     // calling getNonLocalPointerDepFromBB for blocks we don't want to return
1370bd5abe19SDimitry Andric     // any results for.  (getNonLocalPointerDepFromBB will modify our
1371bd5abe19SDimitry Andric     // datastructures in ways the code after the PredTranslationFailure label
1372bd5abe19SDimitry Andric     // doesn't expect.)
1373139f7f9bSDimitry Andric     for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
1374bd5abe19SDimitry Andric       BasicBlock *Pred = PredList[i].first;
1375bd5abe19SDimitry Andric       PHITransAddr &PredPointer = PredList[i].second;
1376bd5abe19SDimitry Andric       Value *PredPtrVal = PredPointer.getAddr();
1377bd5abe19SDimitry Andric 
1378bd5abe19SDimitry Andric       bool CanTranslate = true;
1379f22ef01cSRoman Divacky       // If PHI translation was unable to find an available pointer in this
1380f22ef01cSRoman Divacky       // predecessor, then we have to assume that the pointer is clobbered in
1381f22ef01cSRoman Divacky       // that predecessor.  We can still do PRE of the load, which would insert
1382f22ef01cSRoman Divacky       // a computation of the pointer in this predecessor.
138391bc56edSDimitry Andric       if (!PredPtrVal)
1384bd5abe19SDimitry Andric         CanTranslate = false;
1385bd5abe19SDimitry Andric 
1386bd5abe19SDimitry Andric       // FIXME: it is entirely possible that PHI translating will end up with
1387bd5abe19SDimitry Andric       // the same value.  Consider PHI translating something like:
1388bd5abe19SDimitry Andric       // X = phi [x, bb1], [y, bb2].  PHI translating for bb1 doesn't *need*
1389bd5abe19SDimitry Andric       // to recurse here, pedantically speaking.
1390bd5abe19SDimitry Andric 
1391bd5abe19SDimitry Andric       // If getNonLocalPointerDepFromBB fails here, that means the cached
1392bd5abe19SDimitry Andric       // result conflicted with the Visited list; we have to conservatively
139317a519f9SDimitry Andric       // assume it is unknown, but this also does not block PRE of the load.
1394bd5abe19SDimitry Andric       if (!CanTranslate ||
13953ca95b02SDimitry Andric           !getNonLocalPointerDepFromBB(QueryInst, PredPointer,
13963ca95b02SDimitry Andric                                       Loc.getWithNewPtr(PredPtrVal), isLoad,
13973ca95b02SDimitry Andric                                       Pred, Result, Visited)) {
1398f22ef01cSRoman Divacky         // Add the entry to the Result list.
139917a519f9SDimitry Andric         NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
1400f22ef01cSRoman Divacky         Result.push_back(Entry);
1401f22ef01cSRoman Divacky 
1402f22ef01cSRoman Divacky         // Since we had a phi translation failure, the cache for CacheKey won't
1403f22ef01cSRoman Divacky         // include all of the entries that we need to immediately satisfy future
1404f22ef01cSRoman Divacky         // queries.  Mark this in NonLocalPointerDeps by setting the
1405f22ef01cSRoman Divacky         // BBSkipFirstBlockPair pointer to null.  This requires reuse of the
1406f22ef01cSRoman Divacky         // cached value to do more work but not miss the phi trans failure.
14072754fe60SDimitry Andric         NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
14082754fe60SDimitry Andric         NLPI.Pair = BBSkipFirstBlockPair();
1409f22ef01cSRoman Divacky         continue;
1410f22ef01cSRoman Divacky       }
1411f22ef01cSRoman Divacky     }
1412f22ef01cSRoman Divacky 
1413f22ef01cSRoman Divacky     // Refresh the CacheInfo/Cache pointer so that it isn't invalidated.
1414f22ef01cSRoman Divacky     CacheInfo = &NonLocalPointerDeps[CacheKey];
14152754fe60SDimitry Andric     Cache = &CacheInfo->NonLocalDeps;
1416f22ef01cSRoman Divacky     NumSortedEntries = Cache->size();
1417f22ef01cSRoman Divacky 
1418f22ef01cSRoman Divacky     // Since we did phi translation, the "Cache" set won't contain all of the
1419f22ef01cSRoman Divacky     // results for the query.  This is ok (we can still use it to accelerate
1420f22ef01cSRoman Divacky     // specific block queries) but we can't do the fastpath "return all
1421f22ef01cSRoman Divacky     // results from the set"  Clear out the indicator for this.
14222754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair();
1423f22ef01cSRoman Divacky     SkipFirstBlock = false;
1424f22ef01cSRoman Divacky     continue;
1425f22ef01cSRoman Divacky 
1426f22ef01cSRoman Divacky   PredTranslationFailure:
1427bd5abe19SDimitry Andric     // The following code is "failure"; we can't produce a sane translation
1428bd5abe19SDimitry Andric     // for the given block.  It assumes that we haven't modified any of
1429bd5abe19SDimitry Andric     // our datastructures while processing the current block.
1430f22ef01cSRoman Divacky 
143191bc56edSDimitry Andric     if (!Cache) {
1432f22ef01cSRoman Divacky       // Refresh the CacheInfo/Cache pointer if it got invalidated.
1433f22ef01cSRoman Divacky       CacheInfo = &NonLocalPointerDeps[CacheKey];
14342754fe60SDimitry Andric       Cache = &CacheInfo->NonLocalDeps;
1435f22ef01cSRoman Divacky       NumSortedEntries = Cache->size();
1436f22ef01cSRoman Divacky     }
1437f22ef01cSRoman Divacky 
1438f22ef01cSRoman Divacky     // Since we failed phi translation, the "Cache" set won't contain all of the
1439f22ef01cSRoman Divacky     // results for the query.  This is ok (we can still use it to accelerate
1440f22ef01cSRoman Divacky     // specific block queries) but we can't do the fastpath "return all
1441f22ef01cSRoman Divacky     // results from the set".  Clear out the indicator for this.
14422754fe60SDimitry Andric     CacheInfo->Pair = BBSkipFirstBlockPair();
1443f22ef01cSRoman Divacky 
144417a519f9SDimitry Andric     // If *nothing* works, mark the pointer as unknown.
1445f22ef01cSRoman Divacky     //
1446f22ef01cSRoman Divacky     // If this is the magic first block, return this as a clobber of the whole
1447f22ef01cSRoman Divacky     // incoming value.  Since we can't phi translate to one of the predecessors,
1448f22ef01cSRoman Divacky     // we have to bail out.
1449f22ef01cSRoman Divacky     if (SkipFirstBlock)
14503ca95b02SDimitry Andric       return false;
1451f22ef01cSRoman Divacky 
14523ca95b02SDimitry Andric     bool foundBlock = false;
14533ca95b02SDimitry Andric     for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
14543ca95b02SDimitry Andric       if (I.getBB() != BB)
1455f22ef01cSRoman Divacky         continue;
1456f22ef01cSRoman Divacky 
14573ca95b02SDimitry Andric       assert((GotWorklistLimit || I.getResult().isNonLocal() ||
14583ca95b02SDimitry Andric               !DT.isReachableFromEntry(BB)) &&
1459f22ef01cSRoman Divacky              "Should only be here with transparent block");
14603ca95b02SDimitry Andric       foundBlock = true;
14613ca95b02SDimitry Andric       I.setResult(MemDepResult::getUnknown());
14623ca95b02SDimitry Andric       Result.push_back(
14633ca95b02SDimitry Andric           NonLocalDepResult(I.getBB(), I.getResult(), Pointer.getAddr()));
1464f22ef01cSRoman Divacky       break;
1465f22ef01cSRoman Divacky     }
14663ca95b02SDimitry Andric     (void)foundBlock; (void)GotWorklistLimit;
14673ca95b02SDimitry Andric     assert((foundBlock || GotWorklistLimit) && "Current block not in cache?");
1468f22ef01cSRoman Divacky   }
1469f22ef01cSRoman Divacky 
1470f22ef01cSRoman Divacky   // Okay, we're done now.  If we added new values to the cache, re-sort it.
1471f22ef01cSRoman Divacky   SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
14724ba319b5SDimitry Andric   LLVM_DEBUG(AssertSorted(*Cache));
14733ca95b02SDimitry Andric   return true;
1474f22ef01cSRoman Divacky }
1475f22ef01cSRoman Divacky 
14764ba319b5SDimitry Andric /// If P exists in CachedNonLocalPointerInfo or NonLocalDefsCache, remove it.
RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair P)14773ca95b02SDimitry Andric void MemoryDependenceResults::RemoveCachedNonLocalPointerDependencies(
14783ca95b02SDimitry Andric     ValueIsLoadPair P) {
14794ba319b5SDimitry Andric 
14804ba319b5SDimitry Andric   // Most of the time this cache is empty.
14814ba319b5SDimitry Andric   if (!NonLocalDefsCache.empty()) {
14824ba319b5SDimitry Andric     auto it = NonLocalDefsCache.find(P.getPointer());
14834ba319b5SDimitry Andric     if (it != NonLocalDefsCache.end()) {
14844ba319b5SDimitry Andric       RemoveFromReverseMap(ReverseNonLocalDefsCache,
14854ba319b5SDimitry Andric                            it->second.getResult().getInst(), P.getPointer());
14864ba319b5SDimitry Andric       NonLocalDefsCache.erase(it);
14874ba319b5SDimitry Andric     }
14884ba319b5SDimitry Andric 
14894ba319b5SDimitry Andric     if (auto *I = dyn_cast<Instruction>(P.getPointer())) {
14904ba319b5SDimitry Andric       auto toRemoveIt = ReverseNonLocalDefsCache.find(I);
14914ba319b5SDimitry Andric       if (toRemoveIt != ReverseNonLocalDefsCache.end()) {
14924ba319b5SDimitry Andric         for (const auto &entry : toRemoveIt->second)
14934ba319b5SDimitry Andric           NonLocalDefsCache.erase(entry);
14944ba319b5SDimitry Andric         ReverseNonLocalDefsCache.erase(toRemoveIt);
14954ba319b5SDimitry Andric       }
14964ba319b5SDimitry Andric     }
14974ba319b5SDimitry Andric   }
14984ba319b5SDimitry Andric 
14993ca95b02SDimitry Andric   CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
15003ca95b02SDimitry Andric   if (It == NonLocalPointerDeps.end())
15013ca95b02SDimitry Andric     return;
1502f22ef01cSRoman Divacky 
1503f22ef01cSRoman Divacky   // Remove all of the entries in the BB->val map.  This involves removing
1504f22ef01cSRoman Divacky   // instructions from the reverse map.
15052754fe60SDimitry Andric   NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
1506f22ef01cSRoman Divacky 
1507f22ef01cSRoman Divacky   for (unsigned i = 0, e = PInfo.size(); i != e; ++i) {
1508f22ef01cSRoman Divacky     Instruction *Target = PInfo[i].getResult().getInst();
15093ca95b02SDimitry Andric     if (!Target)
15103ca95b02SDimitry Andric       continue; // Ignore non-local dep results.
1511f22ef01cSRoman Divacky     assert(Target->getParent() == PInfo[i].getBB());
1512f22ef01cSRoman Divacky 
1513f22ef01cSRoman Divacky     // Eliminating the dirty entry from 'Cache', so update the reverse info.
1514f22ef01cSRoman Divacky     RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
1515f22ef01cSRoman Divacky   }
1516f22ef01cSRoman Divacky 
1517f22ef01cSRoman Divacky   // Remove P from NonLocalPointerDeps (which deletes NonLocalDepInfo).
1518f22ef01cSRoman Divacky   NonLocalPointerDeps.erase(It);
1519f22ef01cSRoman Divacky }
1520f22ef01cSRoman Divacky 
invalidateCachedPointerInfo(Value * Ptr)15213ca95b02SDimitry Andric void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
1522f22ef01cSRoman Divacky   // If Ptr isn't really a pointer, just ignore it.
15233ca95b02SDimitry Andric   if (!Ptr->getType()->isPointerTy())
15243ca95b02SDimitry Andric     return;
1525f22ef01cSRoman Divacky   // Flush store info for the pointer.
1526f22ef01cSRoman Divacky   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
1527f22ef01cSRoman Divacky   // Flush load info for the pointer.
1528f22ef01cSRoman Divacky   RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
15294ba319b5SDimitry Andric   // Invalidate phis that use the pointer.
15304ba319b5SDimitry Andric   PV.invalidateValue(Ptr);
1531f22ef01cSRoman Divacky }
1532f22ef01cSRoman Divacky 
invalidateCachedPredecessors()15333ca95b02SDimitry Andric void MemoryDependenceResults::invalidateCachedPredecessors() {
1534ff0cc061SDimitry Andric   PredCache.clear();
1535f22ef01cSRoman Divacky }
1536f22ef01cSRoman Divacky 
removeInstruction(Instruction * RemInst)15373ca95b02SDimitry Andric void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
1538f22ef01cSRoman Divacky   // Walk through the Non-local dependencies, removing this one as the value
1539f22ef01cSRoman Divacky   // for any cached queries.
1540f22ef01cSRoman Divacky   NonLocalDepMapType::iterator NLDI = NonLocalDeps.find(RemInst);
1541f22ef01cSRoman Divacky   if (NLDI != NonLocalDeps.end()) {
1542f22ef01cSRoman Divacky     NonLocalDepInfo &BlockMap = NLDI->second.first;
15433ca95b02SDimitry Andric     for (auto &Entry : BlockMap)
15443ca95b02SDimitry Andric       if (Instruction *Inst = Entry.getResult().getInst())
1545f22ef01cSRoman Divacky         RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
1546f22ef01cSRoman Divacky     NonLocalDeps.erase(NLDI);
1547f22ef01cSRoman Divacky   }
1548f22ef01cSRoman Divacky 
1549f22ef01cSRoman Divacky   // If we have a cached local dependence query for this instruction, remove it.
1550f22ef01cSRoman Divacky   LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
1551f22ef01cSRoman Divacky   if (LocalDepEntry != LocalDeps.end()) {
1552f22ef01cSRoman Divacky     // Remove us from DepInst's reverse set now that the local dep info is gone.
1553f22ef01cSRoman Divacky     if (Instruction *Inst = LocalDepEntry->second.getInst())
1554f22ef01cSRoman Divacky       RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
1555f22ef01cSRoman Divacky 
1556f22ef01cSRoman Divacky     // Remove this local dependency info.
1557f22ef01cSRoman Divacky     LocalDeps.erase(LocalDepEntry);
1558f22ef01cSRoman Divacky   }
1559f22ef01cSRoman Divacky 
1560f22ef01cSRoman Divacky   // If we have any cached pointer dependencies on this instruction, remove
1561f22ef01cSRoman Divacky   // them.  If the instruction has non-pointer type, then it can't be a pointer
1562f22ef01cSRoman Divacky   // base.
1563f22ef01cSRoman Divacky 
1564f22ef01cSRoman Divacky   // Remove it from both the load info and the store info.  The instruction
1565f22ef01cSRoman Divacky   // can't be in either of these maps if it is non-pointer.
1566f22ef01cSRoman Divacky   if (RemInst->getType()->isPointerTy()) {
1567f22ef01cSRoman Divacky     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
1568f22ef01cSRoman Divacky     RemoveCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
1569f22ef01cSRoman Divacky   }
1570f22ef01cSRoman Divacky 
1571f22ef01cSRoman Divacky   // Loop over all of the things that depend on the instruction we're removing.
1572f22ef01cSRoman Divacky   SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
1573f22ef01cSRoman Divacky 
1574f22ef01cSRoman Divacky   // If we find RemInst as a clobber or Def in any of the maps for other values,
1575f22ef01cSRoman Divacky   // we need to replace its entry with a dirty version of the instruction after
1576f22ef01cSRoman Divacky   // it.  If RemInst is a terminator, we use a null dirty value.
1577f22ef01cSRoman Divacky   //
1578f22ef01cSRoman Divacky   // Using a dirty version of the instruction after RemInst saves having to scan
1579f22ef01cSRoman Divacky   // the entire block to get to this point.
1580f22ef01cSRoman Divacky   MemDepResult NewDirtyVal;
1581f22ef01cSRoman Divacky   if (!RemInst->isTerminator())
15827d523365SDimitry Andric     NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
1583f22ef01cSRoman Divacky 
1584f22ef01cSRoman Divacky   ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
1585f22ef01cSRoman Divacky   if (ReverseDepIt != ReverseLocalDeps.end()) {
1586f22ef01cSRoman Divacky     // RemInst can't be the terminator if it has local stuff depending on it.
1587*b5893f02SDimitry Andric     assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() &&
1588f22ef01cSRoman Divacky            "Nothing can locally depend on a terminator");
1589f22ef01cSRoman Divacky 
159039d628a0SDimitry Andric     for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
1591f22ef01cSRoman Divacky       assert(InstDependingOnRemInst != RemInst &&
1592f22ef01cSRoman Divacky              "Already removed our local dep info");
1593f22ef01cSRoman Divacky 
1594f22ef01cSRoman Divacky       LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
1595f22ef01cSRoman Divacky 
1596f22ef01cSRoman Divacky       // Make sure to remember that new things depend on NewDepInst.
15973ca95b02SDimitry Andric       assert(NewDirtyVal.getInst() &&
15983ca95b02SDimitry Andric              "There is no way something else can have "
1599f22ef01cSRoman Divacky              "a local dep on this if it is a terminator!");
16003ca95b02SDimitry Andric       ReverseDepsToAdd.push_back(
16013ca95b02SDimitry Andric           std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
1602f22ef01cSRoman Divacky     }
1603f22ef01cSRoman Divacky 
1604f22ef01cSRoman Divacky     ReverseLocalDeps.erase(ReverseDepIt);
1605f22ef01cSRoman Divacky 
1606f22ef01cSRoman Divacky     // Add new reverse deps after scanning the set, to avoid invalidating the
1607f22ef01cSRoman Divacky     // 'ReverseDeps' reference.
1608f22ef01cSRoman Divacky     while (!ReverseDepsToAdd.empty()) {
16093ca95b02SDimitry Andric       ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
16103ca95b02SDimitry Andric           ReverseDepsToAdd.back().second);
1611f22ef01cSRoman Divacky       ReverseDepsToAdd.pop_back();
1612f22ef01cSRoman Divacky     }
1613f22ef01cSRoman Divacky   }
1614f22ef01cSRoman Divacky 
1615f22ef01cSRoman Divacky   ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
1616f22ef01cSRoman Divacky   if (ReverseDepIt != ReverseNonLocalDeps.end()) {
161739d628a0SDimitry Andric     for (Instruction *I : ReverseDepIt->second) {
161839d628a0SDimitry Andric       assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
1619f22ef01cSRoman Divacky 
162039d628a0SDimitry Andric       PerInstNLInfo &INLD = NonLocalDeps[I];
1621f22ef01cSRoman Divacky       // The information is now dirty!
1622f22ef01cSRoman Divacky       INLD.second = true;
1623f22ef01cSRoman Divacky 
16243ca95b02SDimitry Andric       for (auto &Entry : INLD.first) {
16253ca95b02SDimitry Andric         if (Entry.getResult().getInst() != RemInst)
16263ca95b02SDimitry Andric           continue;
1627f22ef01cSRoman Divacky 
1628f22ef01cSRoman Divacky         // Convert to a dirty entry for the subsequent instruction.
16293ca95b02SDimitry Andric         Entry.setResult(NewDirtyVal);
1630f22ef01cSRoman Divacky 
1631f22ef01cSRoman Divacky         if (Instruction *NextI = NewDirtyVal.getInst())
163239d628a0SDimitry Andric           ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
1633f22ef01cSRoman Divacky       }
1634f22ef01cSRoman Divacky     }
1635f22ef01cSRoman Divacky 
1636f22ef01cSRoman Divacky     ReverseNonLocalDeps.erase(ReverseDepIt);
1637f22ef01cSRoman Divacky 
1638f22ef01cSRoman Divacky     // Add new reverse deps after scanning the set, to avoid invalidating 'Set'
1639f22ef01cSRoman Divacky     while (!ReverseDepsToAdd.empty()) {
16403ca95b02SDimitry Andric       ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
16413ca95b02SDimitry Andric           ReverseDepsToAdd.back().second);
1642f22ef01cSRoman Divacky       ReverseDepsToAdd.pop_back();
1643f22ef01cSRoman Divacky     }
1644f22ef01cSRoman Divacky   }
1645f22ef01cSRoman Divacky 
1646f22ef01cSRoman Divacky   // If the instruction is in ReverseNonLocalPtrDeps then it appears as a
1647f22ef01cSRoman Divacky   // value in the NonLocalPointerDeps info.
1648f22ef01cSRoman Divacky   ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
1649f22ef01cSRoman Divacky       ReverseNonLocalPtrDeps.find(RemInst);
1650f22ef01cSRoman Divacky   if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
16513ca95b02SDimitry Andric     SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
16523ca95b02SDimitry Andric         ReversePtrDepsToAdd;
1653f22ef01cSRoman Divacky 
165439d628a0SDimitry Andric     for (ValueIsLoadPair P : ReversePtrDepIt->second) {
1655f22ef01cSRoman Divacky       assert(P.getPointer() != RemInst &&
1656f22ef01cSRoman Divacky              "Already removed NonLocalPointerDeps info for RemInst");
1657f22ef01cSRoman Divacky 
16582754fe60SDimitry Andric       NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
1659f22ef01cSRoman Divacky 
1660f22ef01cSRoman Divacky       // The cache is not valid for any specific block anymore.
16612754fe60SDimitry Andric       NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
1662f22ef01cSRoman Divacky 
1663f22ef01cSRoman Divacky       // Update any entries for RemInst to use the instruction after it.
16643ca95b02SDimitry Andric       for (auto &Entry : NLPDI) {
16653ca95b02SDimitry Andric         if (Entry.getResult().getInst() != RemInst)
16663ca95b02SDimitry Andric           continue;
1667f22ef01cSRoman Divacky 
1668f22ef01cSRoman Divacky         // Convert to a dirty entry for the subsequent instruction.
16693ca95b02SDimitry Andric         Entry.setResult(NewDirtyVal);
1670f22ef01cSRoman Divacky 
1671f22ef01cSRoman Divacky         if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
1672f22ef01cSRoman Divacky           ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
1673f22ef01cSRoman Divacky       }
1674f22ef01cSRoman Divacky 
1675f22ef01cSRoman Divacky       // Re-sort the NonLocalDepInfo.  Changing the dirty entry to its
1676f22ef01cSRoman Divacky       // subsequent value may invalidate the sortedness.
1677*b5893f02SDimitry Andric       llvm::sort(NLPDI);
1678f22ef01cSRoman Divacky     }
1679f22ef01cSRoman Divacky 
1680f22ef01cSRoman Divacky     ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
1681f22ef01cSRoman Divacky 
1682f22ef01cSRoman Divacky     while (!ReversePtrDepsToAdd.empty()) {
16833ca95b02SDimitry Andric       ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
16843ca95b02SDimitry Andric           ReversePtrDepsToAdd.back().second);
1685f22ef01cSRoman Divacky       ReversePtrDepsToAdd.pop_back();
1686f22ef01cSRoman Divacky     }
1687f22ef01cSRoman Divacky   }
1688f22ef01cSRoman Divacky 
16894ba319b5SDimitry Andric   // Invalidate phis that use the removed instruction.
16904ba319b5SDimitry Andric   PV.invalidateValue(RemInst);
16914ba319b5SDimitry Andric 
1692f22ef01cSRoman Divacky   assert(!NonLocalDeps.count(RemInst) && "RemInst got reinserted?");
16934ba319b5SDimitry Andric   LLVM_DEBUG(verifyRemoved(RemInst));
1694f22ef01cSRoman Divacky }
16953ca95b02SDimitry Andric 
16963ca95b02SDimitry Andric /// Verify that the specified instruction does not occur in our internal data
16973ca95b02SDimitry Andric /// structures.
16983ca95b02SDimitry Andric ///
16993ca95b02SDimitry Andric /// This function verifies by asserting in debug builds.
verifyRemoved(Instruction * D) const17003ca95b02SDimitry Andric void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
170139d628a0SDimitry Andric #ifndef NDEBUG
17023ca95b02SDimitry Andric   for (const auto &DepKV : LocalDeps) {
17033ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
17043ca95b02SDimitry Andric     assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
17053ca95b02SDimitry Andric   }
17063ca95b02SDimitry Andric 
17073ca95b02SDimitry Andric   for (const auto &DepKV : NonLocalPointerDeps) {
17083ca95b02SDimitry Andric     assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
17093ca95b02SDimitry Andric     for (const auto &Entry : DepKV.second.NonLocalDeps)
17103ca95b02SDimitry Andric       assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
17113ca95b02SDimitry Andric   }
17123ca95b02SDimitry Andric 
17133ca95b02SDimitry Andric   for (const auto &DepKV : NonLocalDeps) {
17143ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
17153ca95b02SDimitry Andric     const PerInstNLInfo &INLD = DepKV.second;
17163ca95b02SDimitry Andric     for (const auto &Entry : INLD.first)
17173ca95b02SDimitry Andric       assert(Entry.getResult().getInst() != D &&
1718f22ef01cSRoman Divacky              "Inst occurs in data structures");
1719f22ef01cSRoman Divacky   }
1720f22ef01cSRoman Divacky 
17213ca95b02SDimitry Andric   for (const auto &DepKV : ReverseLocalDeps) {
17223ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
17233ca95b02SDimitry Andric     for (Instruction *Inst : DepKV.second)
172439d628a0SDimitry Andric       assert(Inst != D && "Inst occurs in data structures");
1725f22ef01cSRoman Divacky   }
1726f22ef01cSRoman Divacky 
17273ca95b02SDimitry Andric   for (const auto &DepKV : ReverseNonLocalDeps) {
17283ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in data structures");
17293ca95b02SDimitry Andric     for (Instruction *Inst : DepKV.second)
173039d628a0SDimitry Andric       assert(Inst != D && "Inst occurs in data structures");
1731f22ef01cSRoman Divacky   }
1732f22ef01cSRoman Divacky 
17333ca95b02SDimitry Andric   for (const auto &DepKV : ReverseNonLocalPtrDeps) {
17343ca95b02SDimitry Andric     assert(DepKV.first != D && "Inst occurs in rev NLPD map");
1735f22ef01cSRoman Divacky 
17363ca95b02SDimitry Andric     for (ValueIsLoadPair P : DepKV.second)
17373ca95b02SDimitry Andric       assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
1738f22ef01cSRoman Divacky              "Inst occurs in ReverseNonLocalPtrDeps map");
1739f22ef01cSRoman Divacky   }
174039d628a0SDimitry Andric #endif
1741f22ef01cSRoman Divacky }
17423ca95b02SDimitry Andric 
1743d88c1a5aSDimitry Andric AnalysisKey MemoryDependenceAnalysis::Key;
17443ca95b02SDimitry Andric 
17453ca95b02SDimitry Andric MemoryDependenceResults
run(Function & F,FunctionAnalysisManager & AM)1746d88c1a5aSDimitry Andric MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
17473ca95b02SDimitry Andric   auto &AA = AM.getResult<AAManager>(F);
17483ca95b02SDimitry Andric   auto &AC = AM.getResult<AssumptionAnalysis>(F);
17493ca95b02SDimitry Andric   auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
17503ca95b02SDimitry Andric   auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
17514ba319b5SDimitry Andric   auto &PV = AM.getResult<PhiValuesAnalysis>(F);
17524ba319b5SDimitry Andric   return MemoryDependenceResults(AA, AC, TLI, DT, PV);
17533ca95b02SDimitry Andric }
17543ca95b02SDimitry Andric 
17553ca95b02SDimitry Andric char MemoryDependenceWrapperPass::ID = 0;
17563ca95b02SDimitry Andric 
17573ca95b02SDimitry Andric INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
17583ca95b02SDimitry Andric                       "Memory Dependence Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)17593ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
17603ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
17613ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
17623ca95b02SDimitry Andric INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
17634ba319b5SDimitry Andric INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
17643ca95b02SDimitry Andric INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
17653ca95b02SDimitry Andric                     "Memory Dependence Analysis", false, true)
17663ca95b02SDimitry Andric 
17673ca95b02SDimitry Andric MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
17683ca95b02SDimitry Andric   initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
17693ca95b02SDimitry Andric }
1770d88c1a5aSDimitry Andric 
17712cab237bSDimitry Andric MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() = default;
17723ca95b02SDimitry Andric 
releaseMemory()17733ca95b02SDimitry Andric void MemoryDependenceWrapperPass::releaseMemory() {
17743ca95b02SDimitry Andric   MemDep.reset();
17753ca95b02SDimitry Andric }
17763ca95b02SDimitry Andric 
getAnalysisUsage(AnalysisUsage & AU) const17773ca95b02SDimitry Andric void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
17783ca95b02SDimitry Andric   AU.setPreservesAll();
17793ca95b02SDimitry Andric   AU.addRequired<AssumptionCacheTracker>();
17803ca95b02SDimitry Andric   AU.addRequired<DominatorTreeWrapperPass>();
17814ba319b5SDimitry Andric   AU.addRequired<PhiValuesWrapperPass>();
17823ca95b02SDimitry Andric   AU.addRequiredTransitive<AAResultsWrapperPass>();
17833ca95b02SDimitry Andric   AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
17843ca95b02SDimitry Andric }
17853ca95b02SDimitry Andric 
invalidate(Function & F,const PreservedAnalyses & PA,FunctionAnalysisManager::Invalidator & Inv)1786d88c1a5aSDimitry Andric bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA,
1787d88c1a5aSDimitry Andric                                FunctionAnalysisManager::Invalidator &Inv) {
1788d88c1a5aSDimitry Andric   // Check whether our analysis is preserved.
1789d88c1a5aSDimitry Andric   auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
1790d88c1a5aSDimitry Andric   if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
1791d88c1a5aSDimitry Andric     // If not, give up now.
1792d88c1a5aSDimitry Andric     return true;
1793d88c1a5aSDimitry Andric 
1794d88c1a5aSDimitry Andric   // Check whether the analyses we depend on became invalid for any reason.
1795d88c1a5aSDimitry Andric   if (Inv.invalidate<AAManager>(F, PA) ||
1796d88c1a5aSDimitry Andric       Inv.invalidate<AssumptionAnalysis>(F, PA) ||
17974ba319b5SDimitry Andric       Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
17984ba319b5SDimitry Andric       Inv.invalidate<PhiValuesAnalysis>(F, PA))
1799d88c1a5aSDimitry Andric     return true;
1800d88c1a5aSDimitry Andric 
1801d88c1a5aSDimitry Andric   // Otherwise this analysis result remains valid.
1802d88c1a5aSDimitry Andric   return false;
1803d88c1a5aSDimitry Andric }
1804d88c1a5aSDimitry Andric 
getDefaultBlockScanLimit() const1805d88c1a5aSDimitry Andric unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const {
1806d88c1a5aSDimitry Andric   return BlockScanLimit;
1807d88c1a5aSDimitry Andric }
1808d88c1a5aSDimitry Andric 
runOnFunction(Function & F)18093ca95b02SDimitry Andric bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
18103ca95b02SDimitry Andric   auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
18113ca95b02SDimitry Andric   auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
18123ca95b02SDimitry Andric   auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI();
18133ca95b02SDimitry Andric   auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
18144ba319b5SDimitry Andric   auto &PV = getAnalysis<PhiValuesWrapperPass>().getResult();
18154ba319b5SDimitry Andric   MemDep.emplace(AA, AC, TLI, DT, PV);
18163ca95b02SDimitry Andric   return false;
18173ca95b02SDimitry Andric }
1818