#include "llvm/Analysis/MemoryDependenceAnalysis.h"
#include "llvm/ADT/DenseMap.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/ADT/Statistic.h"
#include "llvm/Analysis/AliasAnalysis.h"
#include "llvm/Analysis/AssumptionCache.h"
#include "llvm/Analysis/MemoryBuiltins.h"
#include "llvm/Analysis/MemoryLocation.h"
#include "llvm/Analysis/PHITransAddr.h"
#include "llvm/Analysis/PhiValues.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Analysis/ValueTracking.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Dominators.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/InstrTypes.h"
#include "llvm/IR/Instruction.h"
#include "llvm/IR/Instructions.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Metadata.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PredIteratorCache.h"
#include "llvm/IR/Type.h"
#include "llvm/IR/Use.h"
#include "llvm/IR/Value.h"
#include "llvm/InitializePasses.h"
#include "llvm/Pass.h"
#include "llvm/Support/AtomicOrdering.h"
#include "llvm/Support/Casting.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#include <cassert>
#include <iterator>
#include <utility>
using namespace llvm;
#define DEBUG_TYPE "memdep"
STATISTIC(NumCacheNonLocal, "Number of fully cached non-local responses");
STATISTIC(NumCacheDirtyNonLocal, "Number of dirty cached non-local responses");
STATISTIC(NumUncacheNonLocal, "Number of uncached non-local responses");
STATISTIC(NumCacheNonLocalPtr,
"Number of fully cached non-local ptr responses");
STATISTIC(NumCacheDirtyNonLocalPtr,
"Number of cached, but dirty, non-local ptr responses");
STATISTIC(NumUncacheNonLocalPtr, "Number of uncached non-local ptr responses");
STATISTIC(NumCacheCompleteNonLocalPtr,
"Number of block queries that were completely cached");
static cl::opt<unsigned> BlockScanLimit(
"memdep-block-scan-limit", cl::Hidden, cl::init(100),
cl::desc("The number of instructions to scan in a block in memory "
"dependency analysis (default = 100)"));
static cl::opt<unsigned>
BlockNumberLimit("memdep-block-number-limit", cl::Hidden, cl::init(1000),
cl::desc("The number of blocks to scan during memory "
"dependency analysis (default = 1000)"));
static const unsigned int NumResultsLimit = 100;
template <typename KeyTy>
static void
RemoveFromReverseMap(DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>> &ReverseMap,
Instruction *Inst, KeyTy Val) {
typename DenseMap<Instruction *, SmallPtrSet<KeyTy, 4>>::iterator InstIt =
ReverseMap.find(Inst);
assert(InstIt != ReverseMap.end() && "Reverse map out of sync?");
bool Found = InstIt->second.erase(Val);
assert(Found && "Invalid reverse map!");
(void)Found;
if (InstIt->second.empty())
ReverseMap.erase(InstIt);
}
static ModRefInfo GetLocation(const Instruction *Inst, MemoryLocation &Loc,
const TargetLibraryInfo &TLI) {
if (const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
if (LI->isUnordered()) {
Loc = MemoryLocation::get(LI);
return ModRefInfo::Ref;
}
if (LI->getOrdering() == AtomicOrdering::Monotonic) {
Loc = MemoryLocation::get(LI);
return ModRefInfo::ModRef;
}
Loc = MemoryLocation();
return ModRefInfo::ModRef;
}
if (const StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
if (SI->isUnordered()) {
Loc = MemoryLocation::get(SI);
return ModRefInfo::Mod;
}
if (SI->getOrdering() == AtomicOrdering::Monotonic) {
Loc = MemoryLocation::get(SI);
return ModRefInfo::ModRef;
}
Loc = MemoryLocation();
return ModRefInfo::ModRef;
}
if (const VAArgInst *V = dyn_cast<VAArgInst>(Inst)) {
Loc = MemoryLocation::get(V);
return ModRefInfo::ModRef;
}
if (const CallBase *CB = dyn_cast<CallBase>(Inst)) {
if (Value *FreedOp = getFreedOperand(CB, &TLI)) {
Loc = MemoryLocation::getAfter(FreedOp);
return ModRefInfo::Mod;
}
}
if (const IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
switch (II->getIntrinsicID()) {
case Intrinsic::lifetime_start:
case Intrinsic::lifetime_end:
case Intrinsic::invariant_start:
Loc = MemoryLocation::getForArgument(II, 1, TLI);
return ModRefInfo::Mod;
case Intrinsic::invariant_end:
Loc = MemoryLocation::getForArgument(II, 2, TLI);
return ModRefInfo::Mod;
case Intrinsic::masked_load:
Loc = MemoryLocation::getForArgument(II, 0, TLI);
return ModRefInfo::Ref;
case Intrinsic::masked_store:
Loc = MemoryLocation::getForArgument(II, 1, TLI);
return ModRefInfo::Mod;
default:
break;
}
}
if (Inst->mayWriteToMemory())
return ModRefInfo::ModRef;
if (Inst->mayReadFromMemory())
return ModRefInfo::Ref;
return ModRefInfo::NoModRef;
}
MemDepResult MemoryDependenceResults::getCallDependencyFrom(
CallBase *Call, bool isReadOnlyCall, BasicBlock::iterator ScanIt,
BasicBlock *BB) {
unsigned Limit = getDefaultBlockScanLimit();
while (ScanIt != BB->begin()) {
Instruction *Inst = &*--ScanIt;
if (isa<DbgInfoIntrinsic>(Inst))
continue;
--Limit;
if (!Limit)
return MemDepResult::getUnknown();
MemoryLocation Loc;
ModRefInfo MR = GetLocation(Inst, Loc, TLI);
if (Loc.Ptr) {
if (isModOrRefSet(AA.getModRefInfo(Call, Loc)))
return MemDepResult::getClobber(Inst);
continue;
}
if (auto *CallB = dyn_cast<CallBase>(Inst)) {
if (isNoModRef(AA.getModRefInfo(Call, CallB))) {
if (isReadOnlyCall && !isModSet(MR) &&
Call->isIdenticalToWhenDefined(CallB))
return MemDepResult::getDef(Inst);
continue;
} else
return MemDepResult::getClobber(Inst);
}
if (isModOrRefSet(MR))
return MemDepResult::getClobber(Inst);
}
if (BB != &BB->getParent()->getEntryBlock())
return MemDepResult::getNonLocal();
return MemDepResult::getNonFuncLocal();
}
MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
BatchAAResults &BatchAA) {
MemDepResult InvariantGroupDependency = MemDepResult::getUnknown();
if (QueryInst != nullptr) {
if (auto *LI = dyn_cast<LoadInst>(QueryInst)) {
InvariantGroupDependency = getInvariantGroupPointerDependency(LI, BB);
if (InvariantGroupDependency.isDef())
return InvariantGroupDependency;
}
}
MemDepResult SimpleDep = getSimplePointerDependencyFrom(
MemLoc, isLoad, ScanIt, BB, QueryInst, Limit, BatchAA);
if (SimpleDep.isDef())
return SimpleDep;
if (InvariantGroupDependency.isNonLocal())
return InvariantGroupDependency;
assert(InvariantGroupDependency.isUnknown() &&
"InvariantGroupDependency should be only unknown at this point");
return SimpleDep;
}
MemDepResult MemoryDependenceResults::getPointerDependencyFrom(
const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
BasicBlock *BB, Instruction *QueryInst, unsigned *Limit) {
BatchAAResults BatchAA(AA);
return getPointerDependencyFrom(MemLoc, isLoad, ScanIt, BB, QueryInst, Limit,
BatchAA);
}
MemDepResult
MemoryDependenceResults::getInvariantGroupPointerDependency(LoadInst *LI,
BasicBlock *BB) {
if (!LI->hasMetadata(LLVMContext::MD_invariant_group))
return MemDepResult::getUnknown();
Value *LoadOperand = LI->getPointerOperand()->stripPointerCasts();
if (isa<GlobalValue>(LoadOperand))
return MemDepResult::getUnknown();
SmallVector<const Value *, 8> LoadOperandsQueue;
LoadOperandsQueue.push_back(LoadOperand);
Instruction *ClosestDependency = nullptr;
auto GetClosestDependency = [this](Instruction *Best, Instruction *Other) {
assert(Other && "Must call it with not null instruction");
if (Best == nullptr || DT.dominates(Best, Other))
return Other;
return Best;
};
while (!LoadOperandsQueue.empty()) {
const Value *Ptr = LoadOperandsQueue.pop_back_val();
assert(Ptr && !isa<GlobalValue>(Ptr) &&
"Null or GlobalValue should not be inserted");
for (const Use &Us : Ptr->uses()) {
auto *U = dyn_cast<Instruction>(Us.getUser());
if (!U || U == LI || !DT.dominates(U, LI))
continue;
if (isa<BitCastInst>(U)) {
LoadOperandsQueue.push_back(U);
continue;
}
if (auto *GEP = dyn_cast<GetElementPtrInst>(U))
if (GEP->hasAllZeroIndices()) {
LoadOperandsQueue.push_back(U);
continue;
}
if ((isa<LoadInst>(U) ||
(isa<StoreInst>(U) &&
cast<StoreInst>(U)->getPointerOperand() == Ptr)) &&
U->hasMetadata(LLVMContext::MD_invariant_group))
ClosestDependency = GetClosestDependency(ClosestDependency, U);
}
}
if (!ClosestDependency)
return MemDepResult::getUnknown();
if (ClosestDependency->getParent() == BB)
return MemDepResult::getDef(ClosestDependency);
NonLocalDefsCache.try_emplace(
LI, NonLocalDepResult(ClosestDependency->getParent(),
MemDepResult::getDef(ClosestDependency), nullptr));
ReverseNonLocalDefsCache[ClosestDependency].insert(LI);
return MemDepResult::getNonLocal();
}
MemDepResult MemoryDependenceResults::getSimplePointerDependencyFrom(
const MemoryLocation &MemLoc, bool isLoad, BasicBlock::iterator ScanIt,
BasicBlock *BB, Instruction *QueryInst, unsigned *Limit,
BatchAAResults &BatchAA) {
bool isInvariantLoad = false;
unsigned DefaultLimit = getDefaultBlockScanLimit();
if (!Limit)
Limit = &DefaultLimit;
if (isLoad && QueryInst) {
LoadInst *LI = dyn_cast<LoadInst>(QueryInst);
if (LI && LI->hasMetadata(LLVMContext::MD_invariant_load))
isInvariantLoad = true;
}
auto isComplexForReordering = [](Instruction * I, AtomicOrdering AO)->bool {
if (I->isVolatile())
return true;
if (auto *LI = dyn_cast<LoadInst>(I))
return isStrongerThan(LI->getOrdering(), AO);
if (auto *SI = dyn_cast<StoreInst>(I))
return isStrongerThan(SI->getOrdering(), AO);
return I->mayReadOrWriteMemory();
};
while (ScanIt != BB->begin()) {
Instruction *Inst = &*--ScanIt;
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst))
if (isa<DbgInfoIntrinsic>(II))
continue;
--*Limit;
if (!*Limit)
return MemDepResult::getUnknown();
if (IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
Intrinsic::ID ID = II->getIntrinsicID();
switch (ID) {
case Intrinsic::lifetime_start: {
MemoryLocation ArgLoc = MemoryLocation::getAfter(II->getArgOperand(1));
if (BatchAA.isMustAlias(ArgLoc, MemLoc))
return MemDepResult::getDef(II);
continue;
}
case Intrinsic::masked_load:
case Intrinsic::masked_store: {
MemoryLocation Loc;
GetLocation(II, Loc, TLI);
AliasResult R = BatchAA.alias(Loc, MemLoc);
if (R == AliasResult::NoAlias)
continue;
if (R == AliasResult::MustAlias)
return MemDepResult::getDef(II);
if (ID == Intrinsic::masked_load)
continue;
return MemDepResult::getClobber(II);
}
}
}
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
if (LI->isVolatile()) {
if (!QueryInst)
return MemDepResult::getClobber(LI);
if (QueryInst->isVolatile())
return MemDepResult::getClobber(LI);
}
if (LI->isAtomic() && isStrongerThanUnordered(LI->getOrdering())) {
if (!QueryInst ||
isComplexForReordering(QueryInst, AtomicOrdering::NotAtomic))
return MemDepResult::getClobber(LI);
if (LI->getOrdering() != AtomicOrdering::Monotonic)
return MemDepResult::getClobber(LI);
}
MemoryLocation LoadLoc = MemoryLocation::get(LI);
AliasResult R = BatchAA.alias(LoadLoc, MemLoc);
if (R == AliasResult::NoAlias)
continue;
if (isLoad) {
if (R == AliasResult::MustAlias)
return MemDepResult::getDef(Inst);
if (R == AliasResult::PartialAlias && R.hasOffset()) {
ClobberOffsets[LI] = R.getOffset();
return MemDepResult::getClobber(Inst);
}
continue;
}
if (BatchAA.pointsToConstantMemory(LoadLoc))
continue;
return MemDepResult::getDef(Inst);
}
if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
if (!SI->isUnordered() && SI->isAtomic()) {
if (!QueryInst ||
isComplexForReordering(QueryInst, AtomicOrdering::Unordered))
return MemDepResult::getClobber(SI);
}
if (SI->isVolatile())
if (!QueryInst || QueryInst->isVolatile())
return MemDepResult::getClobber(SI);
if (!isModOrRefSet(BatchAA.getModRefInfo(SI, MemLoc)))
continue;
MemoryLocation StoreLoc = MemoryLocation::get(SI);
AliasResult R = BatchAA.alias(StoreLoc, MemLoc);
if (R == AliasResult::NoAlias)
continue;
if (R == AliasResult::MustAlias)
return MemDepResult::getDef(Inst);
if (isInvariantLoad)
continue;
return MemDepResult::getClobber(Inst);
}
if (isa<AllocaInst>(Inst) || isNoAliasCall(Inst)) {
const Value *AccessPtr = getUnderlyingObject(MemLoc.Ptr);
if (AccessPtr == Inst || BatchAA.isMustAlias(Inst, AccessPtr))
return MemDepResult::getDef(Inst);
}
if (isInvariantLoad)
continue;
if (FenceInst *FI = dyn_cast<FenceInst>(Inst))
if (isLoad && FI->getOrdering() == AtomicOrdering::Release)
continue;
ModRefInfo MR = BatchAA.getModRefInfo(Inst, MemLoc);
if (isModAndRefSet(MR))
MR = BatchAA.callCapturesBefore(Inst, MemLoc, &DT);
switch (clearMust(MR)) {
case ModRefInfo::NoModRef:
continue;
case ModRefInfo::Mod:
return MemDepResult::getClobber(Inst);
case ModRefInfo::Ref:
if (isLoad)
continue;
LLVM_FALLTHROUGH;
default:
return MemDepResult::getClobber(Inst);
}
}
if (BB != &BB->getParent()->getEntryBlock())
return MemDepResult::getNonLocal();
return MemDepResult::getNonFuncLocal();
}
MemDepResult MemoryDependenceResults::getDependency(Instruction *QueryInst) {
ClobberOffsets.clear();
Instruction *ScanPos = QueryInst;
MemDepResult &LocalCache = LocalDeps[QueryInst];
if (!LocalCache.isDirty())
return LocalCache;
if (Instruction *Inst = LocalCache.getInst()) {
ScanPos = Inst;
RemoveFromReverseMap(ReverseLocalDeps, Inst, QueryInst);
}
BasicBlock *QueryParent = QueryInst->getParent();
if (BasicBlock::iterator(QueryInst) == QueryParent->begin()) {
if (QueryParent != &QueryParent->getParent()->getEntryBlock())
LocalCache = MemDepResult::getNonLocal();
else
LocalCache = MemDepResult::getNonFuncLocal();
} else {
MemoryLocation MemLoc;
ModRefInfo MR = GetLocation(QueryInst, MemLoc, TLI);
if (MemLoc.Ptr) {
bool isLoad = !isModSet(MR);
if (auto *II = dyn_cast<IntrinsicInst>(QueryInst))
isLoad |= II->getIntrinsicID() == Intrinsic::lifetime_start;
LocalCache =
getPointerDependencyFrom(MemLoc, isLoad, ScanPos->getIterator(),
QueryParent, QueryInst, nullptr);
} else if (auto *QueryCall = dyn_cast<CallBase>(QueryInst)) {
bool isReadOnly = AA.onlyReadsMemory(QueryCall);
LocalCache = getCallDependencyFrom(QueryCall, isReadOnly,
ScanPos->getIterator(), QueryParent);
} else
LocalCache = MemDepResult::getUnknown();
}
if (Instruction *I = LocalCache.getInst())
ReverseLocalDeps[I].insert(QueryInst);
return LocalCache;
}
#ifndef NDEBUG
static void AssertSorted(MemoryDependenceResults::NonLocalDepInfo &Cache,
int Count = -1) {
if (Count == -1)
Count = Cache.size();
assert(std::is_sorted(Cache.begin(), Cache.begin() + Count) &&
"Cache isn't sorted!");
}
#endif
const MemoryDependenceResults::NonLocalDepInfo &
MemoryDependenceResults::getNonLocalCallDependency(CallBase *QueryCall) {
assert(getDependency(QueryCall).isNonLocal() &&
"getNonLocalCallDependency should only be used on calls with "
"non-local deps!");
PerInstNLInfo &CacheP = NonLocalDepsMap[QueryCall];
NonLocalDepInfo &Cache = CacheP.first;
SmallVector<BasicBlock *, 32> DirtyBlocks;
if (!Cache.empty()) {
if (!CacheP.second) {
++NumCacheNonLocal;
return Cache;
}
for (auto &Entry : Cache)
if (Entry.getResult().isDirty())
DirtyBlocks.push_back(Entry.getBB());
llvm::sort(Cache);
++NumCacheDirtyNonLocal;
} else {
BasicBlock *QueryBB = QueryCall->getParent();
append_range(DirtyBlocks, PredCache.get(QueryBB));
++NumUncacheNonLocal;
}
bool isReadonlyCall = AA.onlyReadsMemory(QueryCall);
SmallPtrSet<BasicBlock *, 32> Visited;
unsigned NumSortedEntries = Cache.size();
LLVM_DEBUG(AssertSorted(Cache));
while (!DirtyBlocks.empty()) {
BasicBlock *DirtyBB = DirtyBlocks.pop_back_val();
if (!Visited.insert(DirtyBB).second)
continue;
LLVM_DEBUG(AssertSorted(Cache, NumSortedEntries));
NonLocalDepInfo::iterator Entry =
std::upper_bound(Cache.begin(), Cache.begin() + NumSortedEntries,
NonLocalDepEntry(DirtyBB));
if (Entry != Cache.begin() && std::prev(Entry)->getBB() == DirtyBB)
--Entry;
NonLocalDepEntry *ExistingResult = nullptr;
if (Entry != Cache.begin() + NumSortedEntries &&
Entry->getBB() == DirtyBB) {
if (!Entry->getResult().isDirty())
continue;
ExistingResult = &*Entry;
}
BasicBlock::iterator ScanPos = DirtyBB->end();
if (ExistingResult) {
if (Instruction *Inst = ExistingResult->getResult().getInst()) {
ScanPos = Inst->getIterator();
RemoveFromReverseMap<Instruction *>(ReverseNonLocalDeps, Inst,
QueryCall);
}
}
MemDepResult Dep;
if (ScanPos != DirtyBB->begin()) {
Dep = getCallDependencyFrom(QueryCall, isReadonlyCall, ScanPos, DirtyBB);
} else if (DirtyBB != &DirtyBB->getParent()->getEntryBlock()) {
Dep = MemDepResult::getNonLocal();
} else {
Dep = MemDepResult::getNonFuncLocal();
}
if (ExistingResult)
ExistingResult->setResult(Dep);
else
Cache.push_back(NonLocalDepEntry(DirtyBB, Dep));
if (!Dep.isNonLocal()) {
if (Instruction *Inst = Dep.getInst())
ReverseNonLocalDeps[Inst].insert(QueryCall);
} else {
append_range(DirtyBlocks, PredCache.get(DirtyBB));
}
}
return Cache;
}
void MemoryDependenceResults::getNonLocalPointerDependency(
Instruction *QueryInst, SmallVectorImpl<NonLocalDepResult> &Result) {
const MemoryLocation Loc = MemoryLocation::get(QueryInst);
bool isLoad = isa<LoadInst>(QueryInst);
BasicBlock *FromBB = QueryInst->getParent();
assert(FromBB);
assert(Loc.Ptr->getType()->isPointerTy() &&
"Can't get pointer deps of a non-pointer!");
Result.clear();
{
auto NonLocalDefIt = NonLocalDefsCache.find(QueryInst);
if (NonLocalDefIt != NonLocalDefsCache.end()) {
Result.push_back(NonLocalDefIt->second);
ReverseNonLocalDefsCache[NonLocalDefIt->second.getResult().getInst()]
.erase(QueryInst);
NonLocalDefsCache.erase(NonLocalDefIt);
return;
}
}
auto isOrdered = [](Instruction *Inst) {
if (LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
return !LI->isUnordered();
} else if (StoreInst *SI = dyn_cast<StoreInst>(Inst)) {
return !SI->isUnordered();
}
return false;
};
if (QueryInst->isVolatile() || isOrdered(QueryInst)) {
Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
const_cast<Value *>(Loc.Ptr)));
return;
}
const DataLayout &DL = FromBB->getModule()->getDataLayout();
PHITransAddr Address(const_cast<Value *>(Loc.Ptr), DL, &AC);
DenseMap<BasicBlock *, Value *> Visited;
if (getNonLocalPointerDepFromBB(QueryInst, Address, Loc, isLoad, FromBB,
Result, Visited, true))
return;
Result.clear();
Result.push_back(NonLocalDepResult(FromBB, MemDepResult::getUnknown(),
const_cast<Value *>(Loc.Ptr)));
}
MemDepResult MemoryDependenceResults::getNonLocalInfoForBlock(
Instruction *QueryInst, const MemoryLocation &Loc, bool isLoad,
BasicBlock *BB, NonLocalDepInfo *Cache, unsigned NumSortedEntries,
BatchAAResults &BatchAA) {
bool isInvariantLoad = false;
if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst))
isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load);
NonLocalDepInfo::iterator Entry = std::upper_bound(
Cache->begin(), Cache->begin() + NumSortedEntries, NonLocalDepEntry(BB));
if (Entry != Cache->begin() && (Entry - 1)->getBB() == BB)
--Entry;
NonLocalDepEntry *ExistingResult = nullptr;
if (Entry != Cache->begin() + NumSortedEntries && Entry->getBB() == BB)
ExistingResult = &*Entry;
if (ExistingResult && isInvariantLoad &&
!ExistingResult->getResult().isNonFuncLocal())
ExistingResult = nullptr;
if (ExistingResult && !ExistingResult->getResult().isDirty()) {
++NumCacheNonLocalPtr;
return ExistingResult->getResult();
}
BasicBlock::iterator ScanPos = BB->end();
if (ExistingResult && ExistingResult->getResult().getInst()) {
assert(ExistingResult->getResult().getInst()->getParent() == BB &&
"Instruction invalidated?");
++NumCacheDirtyNonLocalPtr;
ScanPos = ExistingResult->getResult().getInst()->getIterator();
ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
RemoveFromReverseMap(ReverseNonLocalPtrDeps, &*ScanPos, CacheKey);
} else {
++NumUncacheNonLocalPtr;
}
MemDepResult Dep = getPointerDependencyFrom(Loc, isLoad, ScanPos, BB,
QueryInst, nullptr, BatchAA);
if (isInvariantLoad)
return Dep;
if (ExistingResult)
ExistingResult->setResult(Dep);
else
Cache->push_back(NonLocalDepEntry(BB, Dep));
if (!Dep.isDef() && !Dep.isClobber())
return Dep;
Instruction *Inst = Dep.getInst();
assert(Inst && "Didn't depend on anything?");
ValueIsLoadPair CacheKey(Loc.Ptr, isLoad);
ReverseNonLocalPtrDeps[Inst].insert(CacheKey);
return Dep;
}
static void
SortNonLocalDepInfoCache(MemoryDependenceResults::NonLocalDepInfo &Cache,
unsigned NumSortedEntries) {
switch (Cache.size() - NumSortedEntries) {
case 0:
break;
case 2: {
NonLocalDepEntry Val = Cache.back();
Cache.pop_back();
MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
std::upper_bound(Cache.begin(), Cache.end() - 1, Val);
Cache.insert(Entry, Val);
LLVM_FALLTHROUGH;
}
case 1:
if (Cache.size() != 1) {
NonLocalDepEntry Val = Cache.back();
Cache.pop_back();
MemoryDependenceResults::NonLocalDepInfo::iterator Entry =
llvm::upper_bound(Cache, Val);
Cache.insert(Entry, Val);
}
break;
default:
llvm::sort(Cache);
break;
}
}
bool MemoryDependenceResults::getNonLocalPointerDepFromBB(
Instruction *QueryInst, const PHITransAddr &Pointer,
const MemoryLocation &Loc, bool isLoad, BasicBlock *StartBB,
SmallVectorImpl<NonLocalDepResult> &Result,
DenseMap<BasicBlock *, Value *> &Visited, bool SkipFirstBlock,
bool IsIncomplete) {
ValueIsLoadPair CacheKey(Pointer.getAddr(), isLoad);
NonLocalPointerInfo InitialNLPI;
InitialNLPI.Size = Loc.Size;
InitialNLPI.AATags = Loc.AATags;
bool isInvariantLoad = false;
if (LoadInst *LI = dyn_cast_or_null<LoadInst>(QueryInst))
isInvariantLoad = LI->getMetadata(LLVMContext::MD_invariant_load);
std::pair<CachedNonLocalPointerInfo::iterator, bool> Pair =
NonLocalPointerDeps.insert(std::make_pair(CacheKey, InitialNLPI));
NonLocalPointerInfo *CacheInfo = &Pair.first->second;
if (!isInvariantLoad && !Pair.second) {
if (CacheInfo->Size != Loc.Size) {
bool ThrowOutEverything;
if (CacheInfo->Size.hasValue() && Loc.Size.hasValue()) {
ThrowOutEverything =
CacheInfo->Size.isPrecise() != Loc.Size.isPrecise() ||
CacheInfo->Size.getValue() < Loc.Size.getValue();
} else {
ThrowOutEverything = !Loc.Size.hasValue();
}
if (ThrowOutEverything) {
CacheInfo->Pair = BBSkipFirstBlockPair();
CacheInfo->Size = Loc.Size;
for (auto &Entry : CacheInfo->NonLocalDeps)
if (Instruction *Inst = Entry.getResult().getInst())
RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
CacheInfo->NonLocalDeps.clear();
IsIncomplete = true;
} else {
return getNonLocalPointerDepFromBB(
QueryInst, Pointer, Loc.getWithNewSize(CacheInfo->Size), isLoad,
StartBB, Result, Visited, SkipFirstBlock, IsIncomplete);
}
}
if (CacheInfo->AATags != Loc.AATags) {
if (CacheInfo->AATags) {
CacheInfo->Pair = BBSkipFirstBlockPair();
CacheInfo->AATags = AAMDNodes();
for (auto &Entry : CacheInfo->NonLocalDeps)
if (Instruction *Inst = Entry.getResult().getInst())
RemoveFromReverseMap(ReverseNonLocalPtrDeps, Inst, CacheKey);
CacheInfo->NonLocalDeps.clear();
IsIncomplete = true;
}
if (Loc.AATags)
return getNonLocalPointerDepFromBB(
QueryInst, Pointer, Loc.getWithoutAATags(), isLoad, StartBB, Result,
Visited, SkipFirstBlock, IsIncomplete);
}
}
NonLocalDepInfo *Cache = &CacheInfo->NonLocalDeps;
if (!IsIncomplete && !isInvariantLoad &&
CacheInfo->Pair == BBSkipFirstBlockPair(StartBB, SkipFirstBlock)) {
if (!Visited.empty()) {
for (auto &Entry : *Cache) {
DenseMap<BasicBlock *, Value *>::iterator VI =
Visited.find(Entry.getBB());
if (VI == Visited.end() || VI->second == Pointer.getAddr())
continue;
return false;
}
}
Value *Addr = Pointer.getAddr();
for (auto &Entry : *Cache) {
Visited.insert(std::make_pair(Entry.getBB(), Addr));
if (Entry.getResult().isNonLocal()) {
continue;
}
if (DT.isReachableFromEntry(Entry.getBB())) {
Result.push_back(
NonLocalDepResult(Entry.getBB(), Entry.getResult(), Addr));
}
}
++NumCacheCompleteNonLocalPtr;
return true;
}
if (!isInvariantLoad) {
if (!IsIncomplete && Cache->empty())
CacheInfo->Pair = BBSkipFirstBlockPair(StartBB, SkipFirstBlock);
else
CacheInfo->Pair = BBSkipFirstBlockPair();
}
SmallVector<BasicBlock *, 32> Worklist;
Worklist.push_back(StartBB);
SmallVector<std::pair<BasicBlock *, PHITransAddr>, 16> PredList;
unsigned NumSortedEntries = Cache->size();
unsigned WorklistEntries = BlockNumberLimit;
bool GotWorklistLimit = false;
LLVM_DEBUG(AssertSorted(*Cache));
BatchAAResults BatchAA(AA);
while (!Worklist.empty()) {
BasicBlock *BB = Worklist.pop_back_val();
if (Result.size() > NumResultsLimit) {
if (Cache && NumSortedEntries != Cache->size()) {
SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
}
CacheInfo->Pair = BBSkipFirstBlockPair();
return false;
}
if (!SkipFirstBlock) {
assert(Visited.count(BB) && "Should check 'visited' before adding to WL");
LLVM_DEBUG(AssertSorted(*Cache, NumSortedEntries));
MemDepResult Dep = getNonLocalInfoForBlock(
QueryInst, Loc, isLoad, BB, Cache, NumSortedEntries, BatchAA);
if (!Dep.isNonLocal()) {
if (DT.isReachableFromEntry(BB)) {
Result.push_back(NonLocalDepResult(BB, Dep, Pointer.getAddr()));
continue;
}
}
}
if (!Pointer.NeedsPHITranslationFromBlock(BB)) {
SkipFirstBlock = false;
SmallVector<BasicBlock *, 16> NewBlocks;
for (BasicBlock *Pred : PredCache.get(BB)) {
std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
Visited.insert(std::make_pair(Pred, Pointer.getAddr()));
if (InsertRes.second) {
NewBlocks.push_back(Pred);
continue;
}
if (InsertRes.first->second != Pointer.getAddr()) {
for (unsigned i = 0; i < NewBlocks.size(); i++)
Visited.erase(NewBlocks[i]);
goto PredTranslationFailure;
}
}
if (NewBlocks.size() > WorklistEntries) {
for (unsigned i = 0; i < NewBlocks.size(); i++)
Visited.erase(NewBlocks[i]);
GotWorklistLimit = true;
goto PredTranslationFailure;
}
WorklistEntries -= NewBlocks.size();
Worklist.append(NewBlocks.begin(), NewBlocks.end());
continue;
}
if (!Pointer.IsPotentiallyPHITranslatable())
goto PredTranslationFailure;
if (Cache && NumSortedEntries != Cache->size()) {
SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
NumSortedEntries = Cache->size();
}
Cache = nullptr;
PredList.clear();
for (BasicBlock *Pred : PredCache.get(BB)) {
PredList.push_back(std::make_pair(Pred, Pointer));
PHITransAddr &PredPointer = PredList.back().second;
PredPointer.PHITranslateValue(BB, Pred, &DT, false);
Value *PredPtrVal = PredPointer.getAddr();
std::pair<DenseMap<BasicBlock *, Value *>::iterator, bool> InsertRes =
Visited.insert(std::make_pair(Pred, PredPtrVal));
if (!InsertRes.second) {
PredList.pop_back();
if (InsertRes.first->second == PredPtrVal)
continue;
for (unsigned i = 0, n = PredList.size(); i < n; ++i)
Visited.erase(PredList[i].first);
goto PredTranslationFailure;
}
}
for (unsigned i = 0, n = PredList.size(); i < n; ++i) {
BasicBlock *Pred = PredList[i].first;
PHITransAddr &PredPointer = PredList[i].second;
Value *PredPtrVal = PredPointer.getAddr();
bool CanTranslate = true;
if (!PredPtrVal)
CanTranslate = false;
if (!CanTranslate ||
!getNonLocalPointerDepFromBB(QueryInst, PredPointer,
Loc.getWithNewPtr(PredPtrVal), isLoad,
Pred, Result, Visited)) {
NonLocalDepResult Entry(Pred, MemDepResult::getUnknown(), PredPtrVal);
Result.push_back(Entry);
NonLocalPointerInfo &NLPI = NonLocalPointerDeps[CacheKey];
NLPI.Pair = BBSkipFirstBlockPair();
continue;
}
}
CacheInfo = &NonLocalPointerDeps[CacheKey];
Cache = &CacheInfo->NonLocalDeps;
NumSortedEntries = Cache->size();
CacheInfo->Pair = BBSkipFirstBlockPair();
SkipFirstBlock = false;
continue;
PredTranslationFailure:
if (!Cache) {
CacheInfo = &NonLocalPointerDeps[CacheKey];
Cache = &CacheInfo->NonLocalDeps;
NumSortedEntries = Cache->size();
}
CacheInfo->Pair = BBSkipFirstBlockPair();
if (SkipFirstBlock)
return false;
if (!isInvariantLoad) {
for (NonLocalDepEntry &I : llvm::reverse(*Cache)) {
if (I.getBB() != BB)
continue;
assert((GotWorklistLimit || I.getResult().isNonLocal() ||
!DT.isReachableFromEntry(BB)) &&
"Should only be here with transparent block");
I.setResult(MemDepResult::getUnknown());
break;
}
}
(void)GotWorklistLimit;
Result.push_back(
NonLocalDepResult(BB, MemDepResult::getUnknown(), Pointer.getAddr()));
}
SortNonLocalDepInfoCache(*Cache, NumSortedEntries);
LLVM_DEBUG(AssertSorted(*Cache));
return true;
}
void MemoryDependenceResults::removeCachedNonLocalPointerDependencies(
ValueIsLoadPair P) {
if (!NonLocalDefsCache.empty()) {
auto it = NonLocalDefsCache.find(P.getPointer());
if (it != NonLocalDefsCache.end()) {
RemoveFromReverseMap(ReverseNonLocalDefsCache,
it->second.getResult().getInst(), P.getPointer());
NonLocalDefsCache.erase(it);
}
if (auto *I = dyn_cast<Instruction>(P.getPointer())) {
auto toRemoveIt = ReverseNonLocalDefsCache.find(I);
if (toRemoveIt != ReverseNonLocalDefsCache.end()) {
for (const auto *entry : toRemoveIt->second)
NonLocalDefsCache.erase(entry);
ReverseNonLocalDefsCache.erase(toRemoveIt);
}
}
}
CachedNonLocalPointerInfo::iterator It = NonLocalPointerDeps.find(P);
if (It == NonLocalPointerDeps.end())
return;
NonLocalDepInfo &PInfo = It->second.NonLocalDeps;
for (const NonLocalDepEntry &DE : PInfo) {
Instruction *Target = DE.getResult().getInst();
if (!Target)
continue; assert(Target->getParent() == DE.getBB());
RemoveFromReverseMap(ReverseNonLocalPtrDeps, Target, P);
}
NonLocalPointerDeps.erase(It);
}
void MemoryDependenceResults::invalidateCachedPointerInfo(Value *Ptr) {
if (!Ptr->getType()->isPointerTy())
return;
removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, false));
removeCachedNonLocalPointerDependencies(ValueIsLoadPair(Ptr, true));
PV.invalidateValue(Ptr);
}
void MemoryDependenceResults::invalidateCachedPredecessors() {
PredCache.clear();
}
void MemoryDependenceResults::removeInstruction(Instruction *RemInst) {
NonLocalDepMapType::iterator NLDI = NonLocalDepsMap.find(RemInst);
if (NLDI != NonLocalDepsMap.end()) {
NonLocalDepInfo &BlockMap = NLDI->second.first;
for (auto &Entry : BlockMap)
if (Instruction *Inst = Entry.getResult().getInst())
RemoveFromReverseMap(ReverseNonLocalDeps, Inst, RemInst);
NonLocalDepsMap.erase(NLDI);
}
LocalDepMapType::iterator LocalDepEntry = LocalDeps.find(RemInst);
if (LocalDepEntry != LocalDeps.end()) {
if (Instruction *Inst = LocalDepEntry->second.getInst())
RemoveFromReverseMap(ReverseLocalDeps, Inst, RemInst);
LocalDeps.erase(LocalDepEntry);
}
if (RemInst->getType()->isPointerTy()) {
removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, false));
removeCachedNonLocalPointerDependencies(ValueIsLoadPair(RemInst, true));
} else {
auto toRemoveIt = NonLocalDefsCache.find(RemInst);
if (toRemoveIt != NonLocalDefsCache.end()) {
assert(isa<LoadInst>(RemInst) &&
"only load instructions should be added directly");
const Instruction *DepV = toRemoveIt->second.getResult().getInst();
ReverseNonLocalDefsCache.find(DepV)->second.erase(RemInst);
NonLocalDefsCache.erase(toRemoveIt);
}
}
SmallVector<std::pair<Instruction *, Instruction *>, 8> ReverseDepsToAdd;
MemDepResult NewDirtyVal;
if (!RemInst->isTerminator())
NewDirtyVal = MemDepResult::getDirty(&*++RemInst->getIterator());
ReverseDepMapType::iterator ReverseDepIt = ReverseLocalDeps.find(RemInst);
if (ReverseDepIt != ReverseLocalDeps.end()) {
assert(!ReverseDepIt->second.empty() && !RemInst->isTerminator() &&
"Nothing can locally depend on a terminator");
for (Instruction *InstDependingOnRemInst : ReverseDepIt->second) {
assert(InstDependingOnRemInst != RemInst &&
"Already removed our local dep info");
LocalDeps[InstDependingOnRemInst] = NewDirtyVal;
assert(NewDirtyVal.getInst() &&
"There is no way something else can have "
"a local dep on this if it is a terminator!");
ReverseDepsToAdd.push_back(
std::make_pair(NewDirtyVal.getInst(), InstDependingOnRemInst));
}
ReverseLocalDeps.erase(ReverseDepIt);
while (!ReverseDepsToAdd.empty()) {
ReverseLocalDeps[ReverseDepsToAdd.back().first].insert(
ReverseDepsToAdd.back().second);
ReverseDepsToAdd.pop_back();
}
}
ReverseDepIt = ReverseNonLocalDeps.find(RemInst);
if (ReverseDepIt != ReverseNonLocalDeps.end()) {
for (Instruction *I : ReverseDepIt->second) {
assert(I != RemInst && "Already removed NonLocalDep info for RemInst");
PerInstNLInfo &INLD = NonLocalDepsMap[I];
INLD.second = true;
for (auto &Entry : INLD.first) {
if (Entry.getResult().getInst() != RemInst)
continue;
Entry.setResult(NewDirtyVal);
if (Instruction *NextI = NewDirtyVal.getInst())
ReverseDepsToAdd.push_back(std::make_pair(NextI, I));
}
}
ReverseNonLocalDeps.erase(ReverseDepIt);
while (!ReverseDepsToAdd.empty()) {
ReverseNonLocalDeps[ReverseDepsToAdd.back().first].insert(
ReverseDepsToAdd.back().second);
ReverseDepsToAdd.pop_back();
}
}
ReverseNonLocalPtrDepTy::iterator ReversePtrDepIt =
ReverseNonLocalPtrDeps.find(RemInst);
if (ReversePtrDepIt != ReverseNonLocalPtrDeps.end()) {
SmallVector<std::pair<Instruction *, ValueIsLoadPair>, 8>
ReversePtrDepsToAdd;
for (ValueIsLoadPair P : ReversePtrDepIt->second) {
assert(P.getPointer() != RemInst &&
"Already removed NonLocalPointerDeps info for RemInst");
NonLocalDepInfo &NLPDI = NonLocalPointerDeps[P].NonLocalDeps;
NonLocalPointerDeps[P].Pair = BBSkipFirstBlockPair();
for (auto &Entry : NLPDI) {
if (Entry.getResult().getInst() != RemInst)
continue;
Entry.setResult(NewDirtyVal);
if (Instruction *NewDirtyInst = NewDirtyVal.getInst())
ReversePtrDepsToAdd.push_back(std::make_pair(NewDirtyInst, P));
}
llvm::sort(NLPDI);
}
ReverseNonLocalPtrDeps.erase(ReversePtrDepIt);
while (!ReversePtrDepsToAdd.empty()) {
ReverseNonLocalPtrDeps[ReversePtrDepsToAdd.back().first].insert(
ReversePtrDepsToAdd.back().second);
ReversePtrDepsToAdd.pop_back();
}
}
PV.invalidateValue(RemInst);
assert(!NonLocalDepsMap.count(RemInst) && "RemInst got reinserted?");
LLVM_DEBUG(verifyRemoved(RemInst));
}
void MemoryDependenceResults::verifyRemoved(Instruction *D) const {
#ifndef NDEBUG
for (const auto &DepKV : LocalDeps) {
assert(DepKV.first != D && "Inst occurs in data structures");
assert(DepKV.second.getInst() != D && "Inst occurs in data structures");
}
for (const auto &DepKV : NonLocalPointerDeps) {
assert(DepKV.first.getPointer() != D && "Inst occurs in NLPD map key");
for (const auto &Entry : DepKV.second.NonLocalDeps)
assert(Entry.getResult().getInst() != D && "Inst occurs as NLPD value");
}
for (const auto &DepKV : NonLocalDepsMap) {
assert(DepKV.first != D && "Inst occurs in data structures");
const PerInstNLInfo &INLD = DepKV.second;
for (const auto &Entry : INLD.first)
assert(Entry.getResult().getInst() != D &&
"Inst occurs in data structures");
}
for (const auto &DepKV : ReverseLocalDeps) {
assert(DepKV.first != D && "Inst occurs in data structures");
for (Instruction *Inst : DepKV.second)
assert(Inst != D && "Inst occurs in data structures");
}
for (const auto &DepKV : ReverseNonLocalDeps) {
assert(DepKV.first != D && "Inst occurs in data structures");
for (Instruction *Inst : DepKV.second)
assert(Inst != D && "Inst occurs in data structures");
}
for (const auto &DepKV : ReverseNonLocalPtrDeps) {
assert(DepKV.first != D && "Inst occurs in rev NLPD map");
for (ValueIsLoadPair P : DepKV.second)
assert(P != ValueIsLoadPair(D, false) && P != ValueIsLoadPair(D, true) &&
"Inst occurs in ReverseNonLocalPtrDeps map");
}
#endif
}
AnalysisKey MemoryDependenceAnalysis::Key;
MemoryDependenceAnalysis::MemoryDependenceAnalysis()
: DefaultBlockScanLimit(BlockScanLimit) {}
MemoryDependenceResults
MemoryDependenceAnalysis::run(Function &F, FunctionAnalysisManager &AM) {
auto &AA = AM.getResult<AAManager>(F);
auto &AC = AM.getResult<AssumptionAnalysis>(F);
auto &TLI = AM.getResult<TargetLibraryAnalysis>(F);
auto &DT = AM.getResult<DominatorTreeAnalysis>(F);
auto &PV = AM.getResult<PhiValuesAnalysis>(F);
return MemoryDependenceResults(AA, AC, TLI, DT, PV, DefaultBlockScanLimit);
}
char MemoryDependenceWrapperPass::ID = 0;
INITIALIZE_PASS_BEGIN(MemoryDependenceWrapperPass, "memdep",
"Memory Dependence Analysis", false, true)
INITIALIZE_PASS_DEPENDENCY(AssumptionCacheTracker)
INITIALIZE_PASS_DEPENDENCY(AAResultsWrapperPass)
INITIALIZE_PASS_DEPENDENCY(DominatorTreeWrapperPass)
INITIALIZE_PASS_DEPENDENCY(TargetLibraryInfoWrapperPass)
INITIALIZE_PASS_DEPENDENCY(PhiValuesWrapperPass)
INITIALIZE_PASS_END(MemoryDependenceWrapperPass, "memdep",
"Memory Dependence Analysis", false, true)
MemoryDependenceWrapperPass::MemoryDependenceWrapperPass() : FunctionPass(ID) {
initializeMemoryDependenceWrapperPassPass(*PassRegistry::getPassRegistry());
}
MemoryDependenceWrapperPass::~MemoryDependenceWrapperPass() = default;
void MemoryDependenceWrapperPass::releaseMemory() {
MemDep.reset();
}
void MemoryDependenceWrapperPass::getAnalysisUsage(AnalysisUsage &AU) const {
AU.setPreservesAll();
AU.addRequired<AssumptionCacheTracker>();
AU.addRequired<DominatorTreeWrapperPass>();
AU.addRequired<PhiValuesWrapperPass>();
AU.addRequiredTransitive<AAResultsWrapperPass>();
AU.addRequiredTransitive<TargetLibraryInfoWrapperPass>();
}
bool MemoryDependenceResults::invalidate(Function &F, const PreservedAnalyses &PA,
FunctionAnalysisManager::Invalidator &Inv) {
auto PAC = PA.getChecker<MemoryDependenceAnalysis>();
if (!PAC.preserved() && !PAC.preservedSet<AllAnalysesOn<Function>>())
return true;
if (Inv.invalidate<AAManager>(F, PA) ||
Inv.invalidate<AssumptionAnalysis>(F, PA) ||
Inv.invalidate<DominatorTreeAnalysis>(F, PA) ||
Inv.invalidate<PhiValuesAnalysis>(F, PA))
return true;
return false;
}
unsigned MemoryDependenceResults::getDefaultBlockScanLimit() const {
return DefaultBlockScanLimit;
}
bool MemoryDependenceWrapperPass::runOnFunction(Function &F) {
auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F);
auto &TLI = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F);
auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
auto &PV = getAnalysis<PhiValuesWrapperPass>().getResult();
MemDep.emplace(AA, AC, TLI, DT, PV, BlockScanLimit);
return false;
}