#include "llvm/Analysis/MemorySSAUpdater.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SetVector.h"
#include "llvm/ADT/SmallPtrSet.h"
#include "llvm/Analysis/IteratedDominanceFrontier.h"
#include "llvm/Analysis/LoopIterator.h"
#include "llvm/Analysis/MemorySSA.h"
#include "llvm/IR/BasicBlock.h"
#include "llvm/IR/Dominators.h"
#include "llvm/Support/Debug.h"
#include <algorithm>
#define DEBUG_TYPE "memoryssa"
using namespace llvm;
MemoryAccess *MemorySSAUpdater::getPreviousDefRecursive(
BasicBlock *BB,
DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
auto Cached = CachedPreviousDef.find(BB);
if (Cached != CachedPreviousDef.end())
return Cached->second;
if (!MSSA->DT->isReachableFromEntry(BB))
return MSSA->getLiveOnEntryDef();
if (BasicBlock *Pred = BB->getUniquePredecessor()) {
VisitedBlocks.insert(BB);
MemoryAccess *Result = getPreviousDefFromEnd(Pred, CachedPreviousDef);
CachedPreviousDef.insert({BB, Result});
return Result;
}
if (VisitedBlocks.count(BB)) {
MemoryAccess *Result = MSSA->createMemoryPhi(BB);
CachedPreviousDef.insert({BB, Result});
return Result;
}
if (VisitedBlocks.insert(BB).second) {
SmallVector<TrackingVH<MemoryAccess>, 8> PhiOps;
bool UniqueIncomingAccess = true;
MemoryAccess *SingleAccess = nullptr;
for (auto *Pred : predecessors(BB)) {
if (MSSA->DT->isReachableFromEntry(Pred)) {
auto *IncomingAccess = getPreviousDefFromEnd(Pred, CachedPreviousDef);
if (!SingleAccess)
SingleAccess = IncomingAccess;
else if (IncomingAccess != SingleAccess)
UniqueIncomingAccess = false;
PhiOps.push_back(IncomingAccess);
} else
PhiOps.push_back(MSSA->getLiveOnEntryDef());
}
MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MSSA->getMemoryAccess(BB));
auto *Result = tryRemoveTrivialPhi(Phi, PhiOps);
if (Result == Phi && UniqueIncomingAccess && SingleAccess) {
if (Phi) {
assert(Phi->operands().empty() && "Expected empty Phi");
Phi->replaceAllUsesWith(SingleAccess);
removeMemoryAccess(Phi);
}
Result = SingleAccess;
} else if (Result == Phi && !(UniqueIncomingAccess && SingleAccess)) {
if (!Phi)
Phi = MSSA->createMemoryPhi(BB);
if (Phi->getNumOperands() != 0) {
if (!std::equal(Phi->op_begin(), Phi->op_end(), PhiOps.begin())) {
llvm::copy(PhiOps, Phi->op_begin());
std::copy(pred_begin(BB), pred_end(BB), Phi->block_begin());
}
} else {
unsigned i = 0;
for (auto *Pred : predecessors(BB))
Phi->addIncoming(&*PhiOps[i++], Pred);
InsertedPHIs.push_back(Phi);
}
Result = Phi;
}
VisitedBlocks.erase(BB);
CachedPreviousDef.insert({BB, Result});
return Result;
}
llvm_unreachable("Should have hit one of the three cases above");
}
MemoryAccess *MemorySSAUpdater::getPreviousDef(MemoryAccess *MA) {
if (auto *LocalResult = getPreviousDefInBlock(MA))
return LocalResult;
DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
return getPreviousDefRecursive(MA->getBlock(), CachedPreviousDef);
}
MemoryAccess *MemorySSAUpdater::getPreviousDefInBlock(MemoryAccess *MA) {
auto *Defs = MSSA->getWritableBlockDefs(MA->getBlock());
if (Defs) {
if (!isa<MemoryUse>(MA)) {
auto Iter = MA->getReverseDefsIterator();
++Iter;
if (Iter != Defs->rend())
return &*Iter;
} else {
auto End = MSSA->getWritableBlockAccesses(MA->getBlock())->rend();
for (auto &U : make_range(++MA->getReverseIterator(), End))
if (!isa<MemoryUse>(U))
return cast<MemoryAccess>(&U);
return nullptr;
}
}
return nullptr;
}
MemoryAccess *MemorySSAUpdater::getPreviousDefFromEnd(
BasicBlock *BB,
DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> &CachedPreviousDef) {
auto *Defs = MSSA->getWritableBlockDefs(BB);
if (Defs) {
CachedPreviousDef.insert({BB, &*Defs->rbegin()});
return &*Defs->rbegin();
}
return getPreviousDefRecursive(BB, CachedPreviousDef);
}
MemoryAccess *MemorySSAUpdater::recursePhi(MemoryAccess *Phi) {
if (!Phi)
return nullptr;
TrackingVH<MemoryAccess> Res(Phi);
SmallVector<TrackingVH<Value>, 8> Uses;
std::copy(Phi->user_begin(), Phi->user_end(), std::back_inserter(Uses));
for (auto &U : Uses)
if (MemoryPhi *UsePhi = dyn_cast<MemoryPhi>(&*U))
tryRemoveTrivialPhi(UsePhi);
return Res;
}
MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi) {
assert(Phi && "Can only remove concrete Phi.");
auto OperRange = Phi->operands();
return tryRemoveTrivialPhi(Phi, OperRange);
}
template <class RangeType>
MemoryAccess *MemorySSAUpdater::tryRemoveTrivialPhi(MemoryPhi *Phi,
RangeType &Operands) {
if (NonOptPhis.count(Phi))
return Phi;
MemoryAccess *Same = nullptr;
for (auto &Op : Operands) {
if (Op == Phi || Op == Same)
continue;
if (Same)
return Phi;
Same = cast<MemoryAccess>(&*Op);
}
if (Same == nullptr)
return MSSA->getLiveOnEntryDef();
if (Phi) {
Phi->replaceAllUsesWith(Same);
removeMemoryAccess(Phi);
}
return recursePhi(Same);
}
void MemorySSAUpdater::insertUse(MemoryUse *MU, bool RenameUses) {
VisitedBlocks.clear();
InsertedPHIs.clear();
MU->setDefiningAccess(getPreviousDef(MU));
if (!RenameUses && !InsertedPHIs.empty()) {
auto *Defs = MSSA->getBlockDefs(MU->getBlock());
(void)Defs;
assert((!Defs || (++Defs->begin() == Defs->end())) &&
"Block may have only a Phi or no defs");
}
if (RenameUses && InsertedPHIs.size()) {
SmallPtrSet<BasicBlock *, 16> Visited;
BasicBlock *StartBlock = MU->getBlock();
if (auto *Defs = MSSA->getWritableBlockDefs(StartBlock)) {
MemoryAccess *FirstDef = &*Defs->begin();
if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
FirstDef = MD->getDefiningAccess();
MSSA->renamePass(MU->getBlock(), FirstDef, Visited);
}
for (auto &MP : InsertedPHIs)
if (MemoryPhi *Phi = cast_or_null<MemoryPhi>(MP))
MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
}
}
static void setMemoryPhiValueForBlock(MemoryPhi *MP, const BasicBlock *BB,
MemoryAccess *NewDef) {
int i = MP->getBasicBlockIndex(BB);
assert(i != -1 && "Should have found the basic block in the phi");
for (const BasicBlock *BlockBB : llvm::drop_begin(MP->blocks(), i)) {
if (BlockBB != BB)
break;
MP->setIncomingValue(i, NewDef);
++i;
}
}
void MemorySSAUpdater::insertDef(MemoryDef *MD, bool RenameUses) {
if (!MSSA->DT->isReachableFromEntry(MD->getBlock())) {
MD->setDefiningAccess(MSSA->getLiveOnEntryDef());
return;
}
VisitedBlocks.clear();
InsertedPHIs.clear();
MemoryAccess *DefBefore = getPreviousDef(MD);
bool DefBeforeSameBlock = false;
if (DefBefore->getBlock() == MD->getBlock() &&
!(isa<MemoryPhi>(DefBefore) &&
llvm::is_contained(InsertedPHIs, DefBefore)))
DefBeforeSameBlock = true;
if (DefBeforeSameBlock) {
DefBefore->replaceUsesWithIf(MD, [MD](Use &U) {
User *Usr = U.getUser();
return !isa<MemoryUse>(Usr) && Usr != MD;
});
}
MD->setDefiningAccess(DefBefore);
SmallVector<WeakVH, 8> FixupList(InsertedPHIs.begin(), InsertedPHIs.end());
SmallSet<WeakVH, 8> ExistingPhis;
unsigned NewPhiIndex = InsertedPHIs.size();
if (!DefBeforeSameBlock) {
SmallPtrSet<BasicBlock *, 2> DefiningBlocks;
DefiningBlocks.insert(MD->getBlock());
for (const auto &VH : InsertedPHIs)
if (const auto *RealPHI = cast_or_null<MemoryPhi>(VH))
DefiningBlocks.insert(RealPHI->getBlock());
ForwardIDFCalculator IDFs(*MSSA->DT);
SmallVector<BasicBlock *, 32> IDFBlocks;
IDFs.setDefiningBlocks(DefiningBlocks);
IDFs.calculate(IDFBlocks);
SmallVector<AssertingVH<MemoryPhi>, 4> NewInsertedPHIs;
for (auto *BBIDF : IDFBlocks) {
auto *MPhi = MSSA->getMemoryAccess(BBIDF);
if (!MPhi) {
MPhi = MSSA->createMemoryPhi(BBIDF);
NewInsertedPHIs.push_back(MPhi);
} else {
ExistingPhis.insert(MPhi);
}
NonOptPhis.insert(MPhi);
}
for (auto &MPhi : NewInsertedPHIs) {
auto *BBIDF = MPhi->getBlock();
for (auto *Pred : predecessors(BBIDF)) {
DenseMap<BasicBlock *, TrackingVH<MemoryAccess>> CachedPreviousDef;
MPhi->addIncoming(getPreviousDefFromEnd(Pred, CachedPreviousDef), Pred);
}
}
NewPhiIndex = InsertedPHIs.size();
for (auto &MPhi : NewInsertedPHIs) {
InsertedPHIs.push_back(&*MPhi);
FixupList.push_back(&*MPhi);
}
FixupList.push_back(MD);
}
unsigned NewPhiIndexEnd = InsertedPHIs.size();
while (!FixupList.empty()) {
unsigned StartingPHISize = InsertedPHIs.size();
fixupDefs(FixupList);
FixupList.clear();
FixupList.append(InsertedPHIs.begin() + StartingPHISize, InsertedPHIs.end());
}
unsigned NewPhiSize = NewPhiIndexEnd - NewPhiIndex;
if (NewPhiSize)
tryRemoveTrivialPhis(ArrayRef<WeakVH>(&InsertedPHIs[NewPhiIndex], NewPhiSize));
BasicBlock *StartBlock = MD->getBlock();
if (RenameUses) {
SmallPtrSet<BasicBlock *, 16> Visited;
MemoryAccess *FirstDef = &*MSSA->getWritableBlockDefs(StartBlock)->begin();
if (auto *MD = dyn_cast<MemoryDef>(FirstDef))
FirstDef = MD->getDefiningAccess();
MSSA->renamePass(MD->getBlock(), FirstDef, Visited);
for (auto &MP : InsertedPHIs) {
MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
if (Phi)
MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
}
for (const auto &MP : ExistingPhis) {
MemoryPhi *Phi = dyn_cast_or_null<MemoryPhi>(MP);
if (Phi)
MSSA->renamePass(Phi->getBlock(), nullptr, Visited);
}
}
}
void MemorySSAUpdater::fixupDefs(const SmallVectorImpl<WeakVH> &Vars) {
SmallPtrSet<const BasicBlock *, 8> Seen;
SmallVector<const BasicBlock *, 16> Worklist;
for (const auto &Var : Vars) {
MemoryAccess *NewDef = dyn_cast_or_null<MemoryAccess>(Var);
if (!NewDef)
continue;
auto *Defs = MSSA->getWritableBlockDefs(NewDef->getBlock());
auto DefIter = NewDef->getDefsIterator();
if (MemoryPhi *Phi = dyn_cast<MemoryPhi>(NewDef))
NonOptPhis.erase(Phi);
if (++DefIter != Defs->end()) {
cast<MemoryDef>(DefIter)->setDefiningAccess(NewDef);
continue;
}
for (const auto *S : successors(NewDef->getBlock())) {
if (auto *MP = MSSA->getMemoryAccess(S))
setMemoryPhiValueForBlock(MP, NewDef->getBlock(), NewDef);
else
Worklist.push_back(S);
}
while (!Worklist.empty()) {
const BasicBlock *FixupBlock = Worklist.pop_back_val();
if (auto *Defs = MSSA->getWritableBlockDefs(FixupBlock)) {
auto *FirstDef = &*Defs->begin();
assert(!isa<MemoryPhi>(FirstDef) &&
"Should have already handled phi nodes!");
assert(MSSA->dominates(NewDef, FirstDef) &&
"Should have dominated the new access");
cast<MemoryDef>(FirstDef)->setDefiningAccess(getPreviousDef(FirstDef));
return;
}
for (const auto *S : successors(FixupBlock)) {
if (auto *MP = MSSA->getMemoryAccess(S))
setMemoryPhiValueForBlock(MP, FixupBlock, NewDef);
else {
if (!Seen.insert(S).second)
continue;
Worklist.push_back(S);
}
}
}
}
}
void MemorySSAUpdater::removeEdge(BasicBlock *From, BasicBlock *To) {
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
MPhi->unorderedDeleteIncomingBlock(From);
tryRemoveTrivialPhi(MPhi);
}
}
void MemorySSAUpdater::removeDuplicatePhiEdgesBetween(const BasicBlock *From,
const BasicBlock *To) {
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(To)) {
bool Found = false;
MPhi->unorderedDeleteIncomingIf([&](const MemoryAccess *, BasicBlock *B) {
if (From != B)
return false;
if (Found)
return true;
Found = true;
return false;
});
tryRemoveTrivialPhi(MPhi);
}
}
static MemoryAccess *onlySingleValue(MemoryPhi *MP) {
MemoryAccess *MA = nullptr;
for (auto &Arg : MP->operands()) {
if (!MA)
MA = cast<MemoryAccess>(Arg);
else if (MA != Arg)
return nullptr;
}
return MA;
}
static MemoryAccess *getNewDefiningAccessForClone(MemoryAccess *MA,
const ValueToValueMapTy &VMap,
PhiToDefMap &MPhiMap,
bool CloneWasSimplified,
MemorySSA *MSSA) {
MemoryAccess *InsnDefining = MA;
if (MemoryDef *DefMUD = dyn_cast<MemoryDef>(InsnDefining)) {
if (!MSSA->isLiveOnEntryDef(DefMUD)) {
Instruction *DefMUDI = DefMUD->getMemoryInst();
assert(DefMUDI && "Found MemoryUseOrDef with no Instruction.");
if (Instruction *NewDefMUDI =
cast_or_null<Instruction>(VMap.lookup(DefMUDI))) {
InsnDefining = MSSA->getMemoryAccess(NewDefMUDI);
if (!CloneWasSimplified)
assert(InsnDefining && "Defining instruction cannot be nullptr.");
else if (!InsnDefining || isa<MemoryUse>(InsnDefining)) {
auto DefIt = DefMUD->getDefsIterator();
assert(DefIt != MSSA->getBlockDefs(DefMUD->getBlock())->begin() &&
"Previous def must exist");
InsnDefining = getNewDefiningAccessForClone(
&*(--DefIt), VMap, MPhiMap, CloneWasSimplified, MSSA);
}
}
}
} else {
MemoryPhi *DefPhi = cast<MemoryPhi>(InsnDefining);
if (MemoryAccess *NewDefPhi = MPhiMap.lookup(DefPhi))
InsnDefining = NewDefPhi;
}
assert(InsnDefining && "Defining instruction cannot be nullptr.");
return InsnDefining;
}
void MemorySSAUpdater::cloneUsesAndDefs(BasicBlock *BB, BasicBlock *NewBB,
const ValueToValueMapTy &VMap,
PhiToDefMap &MPhiMap,
bool CloneWasSimplified) {
const MemorySSA::AccessList *Acc = MSSA->getBlockAccesses(BB);
if (!Acc)
return;
for (const MemoryAccess &MA : *Acc) {
if (const MemoryUseOrDef *MUD = dyn_cast<MemoryUseOrDef>(&MA)) {
Instruction *Insn = MUD->getMemoryInst();
if (Instruction *NewInsn =
dyn_cast_or_null<Instruction>(VMap.lookup(Insn))) {
MemoryAccess *NewUseOrDef = MSSA->createDefinedAccess(
NewInsn,
getNewDefiningAccessForClone(MUD->getDefiningAccess(), VMap,
MPhiMap, CloneWasSimplified, MSSA),
CloneWasSimplified ? nullptr : MUD,
CloneWasSimplified ? false : true);
if (NewUseOrDef)
MSSA->insertIntoListsForBlock(NewUseOrDef, NewBB, MemorySSA::End);
}
}
}
}
void MemorySSAUpdater::updatePhisWhenInsertingUniqueBackedgeBlock(
BasicBlock *Header, BasicBlock *Preheader, BasicBlock *BEBlock) {
auto *MPhi = MSSA->getMemoryAccess(Header);
if (!MPhi)
return;
auto *NewMPhi = MSSA->createMemoryPhi(BEBlock);
bool HasUniqueIncomingValue = true;
MemoryAccess *UniqueValue = nullptr;
for (unsigned I = 0, E = MPhi->getNumIncomingValues(); I != E; ++I) {
BasicBlock *IBB = MPhi->getIncomingBlock(I);
MemoryAccess *IV = MPhi->getIncomingValue(I);
if (IBB != Preheader) {
NewMPhi->addIncoming(IV, IBB);
if (HasUniqueIncomingValue) {
if (!UniqueValue)
UniqueValue = IV;
else if (UniqueValue != IV)
HasUniqueIncomingValue = false;
}
}
}
auto *AccFromPreheader = MPhi->getIncomingValueForBlock(Preheader);
MPhi->setIncomingValue(0, AccFromPreheader);
MPhi->setIncomingBlock(0, Preheader);
for (unsigned I = MPhi->getNumIncomingValues() - 1; I >= 1; --I)
MPhi->unorderedDeleteIncoming(I);
MPhi->addIncoming(NewMPhi, BEBlock);
tryRemoveTrivialPhi(NewMPhi);
}
void MemorySSAUpdater::updateForClonedLoop(const LoopBlocksRPO &LoopBlocks,
ArrayRef<BasicBlock *> ExitBlocks,
const ValueToValueMapTy &VMap,
bool IgnoreIncomingWithNoClones) {
PhiToDefMap MPhiMap;
auto FixPhiIncomingValues = [&](MemoryPhi *Phi, MemoryPhi *NewPhi) {
assert(Phi && NewPhi && "Invalid Phi nodes.");
BasicBlock *NewPhiBB = NewPhi->getBlock();
SmallPtrSet<BasicBlock *, 4> NewPhiBBPreds(pred_begin(NewPhiBB),
pred_end(NewPhiBB));
for (unsigned It = 0, E = Phi->getNumIncomingValues(); It < E; ++It) {
MemoryAccess *IncomingAccess = Phi->getIncomingValue(It);
BasicBlock *IncBB = Phi->getIncomingBlock(It);
if (BasicBlock *NewIncBB = cast_or_null<BasicBlock>(VMap.lookup(IncBB)))
IncBB = NewIncBB;
else if (IgnoreIncomingWithNoClones)
continue;
if (!NewPhiBBPreds.count(IncBB))
continue;
if (MemoryUseOrDef *IncMUD = dyn_cast<MemoryUseOrDef>(IncomingAccess)) {
if (!MSSA->isLiveOnEntryDef(IncMUD)) {
Instruction *IncI = IncMUD->getMemoryInst();
assert(IncI && "Found MemoryUseOrDef with no Instruction.");
if (Instruction *NewIncI =
cast_or_null<Instruction>(VMap.lookup(IncI))) {
IncMUD = MSSA->getMemoryAccess(NewIncI);
assert(IncMUD &&
"MemoryUseOrDef cannot be null, all preds processed.");
}
}
NewPhi->addIncoming(IncMUD, IncBB);
} else {
MemoryPhi *IncPhi = cast<MemoryPhi>(IncomingAccess);
if (MemoryAccess *NewDefPhi = MPhiMap.lookup(IncPhi))
NewPhi->addIncoming(NewDefPhi, IncBB);
else
NewPhi->addIncoming(IncPhi, IncBB);
}
}
if (auto *SingleAccess = onlySingleValue(NewPhi)) {
MPhiMap[Phi] = SingleAccess;
removeMemoryAccess(NewPhi);
}
};
auto ProcessBlock = [&](BasicBlock *BB) {
BasicBlock *NewBlock = cast_or_null<BasicBlock>(VMap.lookup(BB));
if (!NewBlock)
return;
assert(!MSSA->getWritableBlockAccesses(NewBlock) &&
"Cloned block should have no accesses");
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB)) {
MemoryPhi *NewPhi = MSSA->createMemoryPhi(NewBlock);
MPhiMap[MPhi] = NewPhi;
}
cloneUsesAndDefs(BB, NewBlock, VMap, MPhiMap);
};
for (auto *BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
ProcessBlock(BB);
for (auto *BB : llvm::concat<BasicBlock *const>(LoopBlocks, ExitBlocks))
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
if (MemoryAccess *NewPhi = MPhiMap.lookup(MPhi))
FixPhiIncomingValues(MPhi, cast<MemoryPhi>(NewPhi));
}
void MemorySSAUpdater::updateForClonedBlockIntoPred(
BasicBlock *BB, BasicBlock *P1, const ValueToValueMapTy &VM) {
PhiToDefMap MPhiMap;
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(BB))
MPhiMap[MPhi] = MPhi->getIncomingValueForBlock(P1);
cloneUsesAndDefs(BB, P1, VM, MPhiMap, true);
}
template <typename Iter>
void MemorySSAUpdater::privateUpdateExitBlocksForClonedLoop(
ArrayRef<BasicBlock *> ExitBlocks, Iter ValuesBegin, Iter ValuesEnd,
DominatorTree &DT) {
SmallVector<CFGUpdate, 4> Updates;
for (auto *Exit : ExitBlocks)
for (const ValueToValueMapTy *VMap : make_range(ValuesBegin, ValuesEnd))
if (BasicBlock *NewExit = cast_or_null<BasicBlock>(VMap->lookup(Exit))) {
BasicBlock *ExitSucc = NewExit->getTerminator()->getSuccessor(0);
Updates.push_back({DT.Insert, NewExit, ExitSucc});
}
applyInsertUpdates(Updates, DT);
}
void MemorySSAUpdater::updateExitBlocksForClonedLoop(
ArrayRef<BasicBlock *> ExitBlocks, const ValueToValueMapTy &VMap,
DominatorTree &DT) {
const ValueToValueMapTy *const Arr[] = {&VMap};
privateUpdateExitBlocksForClonedLoop(ExitBlocks, std::begin(Arr),
std::end(Arr), DT);
}
void MemorySSAUpdater::updateExitBlocksForClonedLoop(
ArrayRef<BasicBlock *> ExitBlocks,
ArrayRef<std::unique_ptr<ValueToValueMapTy>> VMaps, DominatorTree &DT) {
auto GetPtr = [&](const std::unique_ptr<ValueToValueMapTy> &I) {
return I.get();
};
using MappedIteratorType =
mapped_iterator<const std::unique_ptr<ValueToValueMapTy> *,
decltype(GetPtr)>;
auto MapBegin = MappedIteratorType(VMaps.begin(), GetPtr);
auto MapEnd = MappedIteratorType(VMaps.end(), GetPtr);
privateUpdateExitBlocksForClonedLoop(ExitBlocks, MapBegin, MapEnd, DT);
}
void MemorySSAUpdater::applyUpdates(ArrayRef<CFGUpdate> Updates,
DominatorTree &DT, bool UpdateDT) {
SmallVector<CFGUpdate, 4> DeleteUpdates;
SmallVector<CFGUpdate, 4> RevDeleteUpdates;
SmallVector<CFGUpdate, 4> InsertUpdates;
for (const auto &Update : Updates) {
if (Update.getKind() == DT.Insert)
InsertUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
else {
DeleteUpdates.push_back({DT.Delete, Update.getFrom(), Update.getTo()});
RevDeleteUpdates.push_back({DT.Insert, Update.getFrom(), Update.getTo()});
}
}
if (!DeleteUpdates.empty()) {
if (!InsertUpdates.empty()) {
if (!UpdateDT) {
SmallVector<CFGUpdate, 0> Empty;
DT.applyUpdates(Empty, RevDeleteUpdates);
} else {
DT.applyUpdates(Updates, RevDeleteUpdates);
}
GraphDiff<BasicBlock *> GD(RevDeleteUpdates);
applyInsertUpdates(InsertUpdates, DT, &GD);
DT.applyUpdates(DeleteUpdates);
} else {
if (UpdateDT)
DT.applyUpdates(DeleteUpdates);
}
} else {
if (UpdateDT)
DT.applyUpdates(Updates);
GraphDiff<BasicBlock *> GD;
applyInsertUpdates(InsertUpdates, DT, &GD);
}
for (auto &Update : DeleteUpdates)
removeEdge(Update.getFrom(), Update.getTo());
}
void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
DominatorTree &DT) {
GraphDiff<BasicBlock *> GD;
applyInsertUpdates(Updates, DT, &GD);
}
void MemorySSAUpdater::applyInsertUpdates(ArrayRef<CFGUpdate> Updates,
DominatorTree &DT,
const GraphDiff<BasicBlock *> *GD) {
auto GetLastDef = [&](BasicBlock *BB) -> MemoryAccess * {
while (true) {
MemorySSA::DefsList *Defs = MSSA->getWritableBlockDefs(BB);
if (Defs)
return &*(--Defs->end());
unsigned Count = 0;
BasicBlock *Pred = nullptr;
for (auto *Pi : GD->template getChildren<true>(BB)) {
Pred = Pi;
Count++;
if (Count == 2)
break;
}
if (Count != 1) {
if (!DT.getNode(BB))
return MSSA->getLiveOnEntryDef();
if (auto *IDom = DT.getNode(BB)->getIDom())
if (IDom->getBlock() != BB) {
BB = IDom->getBlock();
continue;
}
return MSSA->getLiveOnEntryDef();
} else {
assert(Count == 1 && Pred && "Single predecessor expected.");
if (!DT.getNode(BB))
return MSSA->getLiveOnEntryDef();
BB = Pred;
}
};
llvm_unreachable("Unable to get last definition.");
};
auto FindNearestCommonDominator =
[&](const SmallSetVector<BasicBlock *, 2> &BBSet) -> BasicBlock * {
BasicBlock *PrevIDom = *BBSet.begin();
for (auto *BB : BBSet)
PrevIDom = DT.findNearestCommonDominator(PrevIDom, BB);
return PrevIDom;
};
auto GetNoLongerDomBlocks =
[&](BasicBlock *PrevIDom, BasicBlock *CurrIDom,
SmallVectorImpl<BasicBlock *> &BlocksPrevDom) {
if (PrevIDom == CurrIDom)
return;
BlocksPrevDom.push_back(PrevIDom);
BasicBlock *NextIDom = PrevIDom;
while (BasicBlock *UpIDom =
DT.getNode(NextIDom)->getIDom()->getBlock()) {
if (UpIDom == CurrIDom)
break;
BlocksPrevDom.push_back(UpIDom);
NextIDom = UpIDom;
}
};
struct PredInfo {
SmallSetVector<BasicBlock *, 2> Added;
SmallSetVector<BasicBlock *, 2> Prev;
};
SmallDenseMap<BasicBlock *, PredInfo> PredMap;
for (const auto &Edge : Updates) {
BasicBlock *BB = Edge.getTo();
auto &AddedBlockSet = PredMap[BB].Added;
AddedBlockSet.insert(Edge.getFrom());
}
SmallDenseMap<std::pair<BasicBlock *, BasicBlock *>, int> EdgeCountMap;
SmallPtrSet<BasicBlock *, 2> NewBlocks;
for (auto &BBPredPair : PredMap) {
auto *BB = BBPredPair.first;
const auto &AddedBlockSet = BBPredPair.second.Added;
auto &PrevBlockSet = BBPredPair.second.Prev;
for (auto *Pi : GD->template getChildren<true>(BB)) {
if (!AddedBlockSet.count(Pi))
PrevBlockSet.insert(Pi);
EdgeCountMap[{Pi, BB}]++;
}
if (PrevBlockSet.empty()) {
assert(pred_size(BB) == AddedBlockSet.size() && "Duplicate edges added.");
LLVM_DEBUG(
dbgs()
<< "Adding a predecessor to a block with no predecessors. "
"This must be an edge added to a new, likely cloned, block. "
"Its memory accesses must be already correct, assuming completed "
"via the updateExitBlocksForClonedLoop API. "
"Assert a single such edge is added so no phi addition or "
"additional processing is required.\n");
assert(AddedBlockSet.size() == 1 &&
"Can only handle adding one predecessor to a new block.");
NewBlocks.insert(BB);
}
}
for (auto *BB : NewBlocks)
PredMap.erase(BB);
SmallVector<BasicBlock *, 16> BlocksWithDefsToReplace;
SmallVector<WeakVH, 8> InsertedPhis;
for (const auto &Edge : Updates) {
BasicBlock *BB = Edge.getTo();
if (PredMap.count(BB) && !MSSA->getMemoryAccess(BB))
InsertedPhis.push_back(MSSA->createMemoryPhi(BB));
}
for (auto &BBPredPair : PredMap) {
auto *BB = BBPredPair.first;
const auto &PrevBlockSet = BBPredPair.second.Prev;
const auto &AddedBlockSet = BBPredPair.second.Added;
assert(!PrevBlockSet.empty() &&
"At least one previous predecessor must exist.");
SmallDenseMap<BasicBlock *, MemoryAccess *> LastDefAddedPred;
for (auto *AddedPred : AddedBlockSet) {
auto *DefPn = GetLastDef(AddedPred);
assert(DefPn != nullptr && "Unable to find last definition.");
LastDefAddedPred[AddedPred] = DefPn;
}
MemoryPhi *NewPhi = MSSA->getMemoryAccess(BB);
if (NewPhi->getNumOperands()) {
for (auto *Pred : AddedBlockSet) {
auto *LastDefForPred = LastDefAddedPred[Pred];
for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
NewPhi->addIncoming(LastDefForPred, Pred);
}
} else {
auto *P1 = *PrevBlockSet.begin();
MemoryAccess *DefP1 = GetLastDef(P1);
bool InsertPhi = false;
for (auto LastDefPredPair : LastDefAddedPred)
if (DefP1 != LastDefPredPair.second) {
InsertPhi = true;
break;
}
if (!InsertPhi) {
NewPhi->replaceAllUsesWith(DefP1);
removeMemoryAccess(NewPhi);
continue;
}
for (auto *Pred : AddedBlockSet) {
auto *LastDefForPred = LastDefAddedPred[Pred];
for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
NewPhi->addIncoming(LastDefForPred, Pred);
}
for (auto *Pred : PrevBlockSet)
for (int I = 0, E = EdgeCountMap[{Pred, BB}]; I < E; ++I)
NewPhi->addIncoming(DefP1, Pred);
}
assert(DT.getNode(BB)->getIDom() && "BB does not have valid idom");
BasicBlock *PrevIDom = FindNearestCommonDominator(PrevBlockSet);
assert(PrevIDom && "Previous IDom should exists");
BasicBlock *NewIDom = DT.getNode(BB)->getIDom()->getBlock();
assert(NewIDom && "BB should have a new valid idom");
assert(DT.dominates(NewIDom, PrevIDom) &&
"New idom should dominate old idom");
GetNoLongerDomBlocks(PrevIDom, NewIDom, BlocksWithDefsToReplace);
}
tryRemoveTrivialPhis(InsertedPhis);
SmallVector<BasicBlock *, 8> BlocksToProcess;
for (auto &VH : InsertedPhis)
if (auto *MPhi = cast_or_null<MemoryPhi>(VH))
BlocksToProcess.push_back(MPhi->getBlock());
SmallVector<BasicBlock *, 32> IDFBlocks;
if (!BlocksToProcess.empty()) {
ForwardIDFCalculator IDFs(DT, GD);
SmallPtrSet<BasicBlock *, 16> DefiningBlocks(BlocksToProcess.begin(),
BlocksToProcess.end());
IDFs.setDefiningBlocks(DefiningBlocks);
IDFs.calculate(IDFBlocks);
SmallSetVector<MemoryPhi *, 4> PhisToFill;
for (auto *BBIDF : IDFBlocks)
if (!MSSA->getMemoryAccess(BBIDF)) {
auto *IDFPhi = MSSA->createMemoryPhi(BBIDF);
InsertedPhis.push_back(IDFPhi);
PhisToFill.insert(IDFPhi);
}
for (auto *BBIDF : IDFBlocks) {
auto *IDFPhi = MSSA->getMemoryAccess(BBIDF);
assert(IDFPhi && "Phi must exist");
if (!PhisToFill.count(IDFPhi)) {
for (unsigned I = 0, E = IDFPhi->getNumIncomingValues(); I < E; ++I)
IDFPhi->setIncomingValue(I, GetLastDef(IDFPhi->getIncomingBlock(I)));
} else {
for (auto *Pi : GD->template getChildren<true>(BBIDF))
IDFPhi->addIncoming(GetLastDef(Pi), Pi);
}
}
}
for (auto *BlockWithDefsToReplace : BlocksWithDefsToReplace) {
if (auto DefsList = MSSA->getWritableBlockDefs(BlockWithDefsToReplace)) {
for (auto &DefToReplaceUses : *DefsList) {
BasicBlock *DominatingBlock = DefToReplaceUses.getBlock();
for (Use &U : llvm::make_early_inc_range(DefToReplaceUses.uses())) {
MemoryAccess *Usr = cast<MemoryAccess>(U.getUser());
if (MemoryPhi *UsrPhi = dyn_cast<MemoryPhi>(Usr)) {
BasicBlock *DominatedBlock = UsrPhi->getIncomingBlock(U);
if (!DT.dominates(DominatingBlock, DominatedBlock))
U.set(GetLastDef(DominatedBlock));
} else {
BasicBlock *DominatedBlock = Usr->getBlock();
if (!DT.dominates(DominatingBlock, DominatedBlock)) {
if (auto *DomBlPhi = MSSA->getMemoryAccess(DominatedBlock))
U.set(DomBlPhi);
else {
auto *IDom = DT.getNode(DominatedBlock)->getIDom();
assert(IDom && "Block must have a valid IDom.");
U.set(GetLastDef(IDom->getBlock()));
}
cast<MemoryUseOrDef>(Usr)->resetOptimized();
}
}
}
}
}
}
tryRemoveTrivialPhis(InsertedPhis);
}
template <class WhereType>
void MemorySSAUpdater::moveTo(MemoryUseOrDef *What, BasicBlock *BB,
WhereType Where) {
for (auto *U : What->users())
if (MemoryPhi *PhiUser = dyn_cast<MemoryPhi>(U))
NonOptPhis.insert(PhiUser);
What->replaceAllUsesWith(What->getDefiningAccess());
MSSA->moveTo(What, BB, Where);
if (auto *MD = dyn_cast<MemoryDef>(What))
insertDef(MD, true);
else
insertUse(cast<MemoryUse>(What), true);
NonOptPhis.clear();
}
void MemorySSAUpdater::moveBefore(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
moveTo(What, Where->getBlock(), Where->getIterator());
}
void MemorySSAUpdater::moveAfter(MemoryUseOrDef *What, MemoryUseOrDef *Where) {
moveTo(What, Where->getBlock(), ++Where->getIterator());
}
void MemorySSAUpdater::moveToPlace(MemoryUseOrDef *What, BasicBlock *BB,
MemorySSA::InsertionPlace Where) {
if (Where != MemorySSA::InsertionPlace::BeforeTerminator)
return moveTo(What, BB, Where);
if (auto *Where = MSSA->getMemoryAccess(BB->getTerminator()))
return moveBefore(What, Where);
else
return moveTo(What, BB, MemorySSA::InsertionPlace::End);
}
void MemorySSAUpdater::moveAllAccesses(BasicBlock *From, BasicBlock *To,
Instruction *Start) {
MemorySSA::AccessList *Accs = MSSA->getWritableBlockAccesses(From);
if (!Accs)
return;
assert(Start->getParent() == To && "Incorrect Start instruction");
MemoryAccess *FirstInNew = nullptr;
for (Instruction &I : make_range(Start->getIterator(), To->end()))
if ((FirstInNew = MSSA->getMemoryAccess(&I)))
break;
if (FirstInNew) {
auto *MUD = cast<MemoryUseOrDef>(FirstInNew);
do {
auto NextIt = ++MUD->getIterator();
MemoryUseOrDef *NextMUD = (!Accs || NextIt == Accs->end())
? nullptr
: cast<MemoryUseOrDef>(&*NextIt);
MSSA->moveTo(MUD, To, MemorySSA::End);
Accs = MSSA->getWritableBlockAccesses(From);
MUD = NextMUD;
} while (MUD);
}
auto *Defs = MSSA->getWritableBlockDefs(From);
if (Defs && !Defs->empty())
if (auto *Phi = dyn_cast<MemoryPhi>(&*Defs->begin()))
tryRemoveTrivialPhi(Phi);
}
void MemorySSAUpdater::moveAllAfterSpliceBlocks(BasicBlock *From,
BasicBlock *To,
Instruction *Start) {
assert(MSSA->getBlockAccesses(To) == nullptr &&
"To block is expected to be free of MemoryAccesses.");
moveAllAccesses(From, To, Start);
for (BasicBlock *Succ : successors(To))
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
}
void MemorySSAUpdater::moveAllAfterMergeBlocks(BasicBlock *From, BasicBlock *To,
Instruction *Start) {
assert(From->getUniquePredecessor() == To &&
"From block is expected to have a single predecessor (To).");
moveAllAccesses(From, To, Start);
for (BasicBlock *Succ : successors(From))
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Succ))
MPhi->setIncomingBlock(MPhi->getBasicBlockIndex(From), To);
}
void MemorySSAUpdater::wireOldPredecessorsToNewImmediatePredecessor(
BasicBlock *Old, BasicBlock *New, ArrayRef<BasicBlock *> Preds,
bool IdenticalEdgesWereMerged) {
assert(!MSSA->getWritableBlockAccesses(New) &&
"Access list should be null for a new block.");
MemoryPhi *Phi = MSSA->getMemoryAccess(Old);
if (!Phi)
return;
if (Old->hasNPredecessors(1)) {
assert(pred_size(New) == Preds.size() &&
"Should have moved all predecessors.");
MSSA->moveTo(Phi, New, MemorySSA::Beginning);
} else {
assert(!Preds.empty() && "Must be moving at least one predecessor to the "
"new immediate predecessor.");
MemoryPhi *NewPhi = MSSA->createMemoryPhi(New);
SmallPtrSet<BasicBlock *, 16> PredsSet(Preds.begin(), Preds.end());
if (!IdenticalEdgesWereMerged)
assert(PredsSet.size() == Preds.size() &&
"If identical edges were not merged, we cannot have duplicate "
"blocks in the predecessors");
Phi->unorderedDeleteIncomingIf([&](MemoryAccess *MA, BasicBlock *B) {
if (PredsSet.count(B)) {
NewPhi->addIncoming(MA, B);
if (!IdenticalEdgesWereMerged)
PredsSet.erase(B);
return true;
}
return false;
});
Phi->addIncoming(NewPhi, New);
tryRemoveTrivialPhi(NewPhi);
}
}
void MemorySSAUpdater::removeMemoryAccess(MemoryAccess *MA, bool OptimizePhis) {
assert(!MSSA->isLiveOnEntryDef(MA) &&
"Trying to remove the live on entry def");
MemoryAccess *NewDefTarget = nullptr;
if (MemoryPhi *MP = dyn_cast<MemoryPhi>(MA)) {
NewDefTarget = onlySingleValue(MP);
assert((NewDefTarget || MP->use_empty()) &&
"We can't delete this memory phi");
} else {
NewDefTarget = cast<MemoryUseOrDef>(MA)->getDefiningAccess();
}
SmallSetVector<MemoryPhi *, 4> PhisToCheck;
if (!isa<MemoryUse>(MA) && !MA->use_empty()) {
if (MA->hasValueHandle())
ValueHandleBase::ValueIsRAUWd(MA, NewDefTarget);
assert(NewDefTarget != MA && "Going into an infinite loop");
while (!MA->use_empty()) {
Use &U = *MA->use_begin();
if (auto *MUD = dyn_cast<MemoryUseOrDef>(U.getUser()))
MUD->resetOptimized();
if (OptimizePhis)
if (MemoryPhi *MP = dyn_cast<MemoryPhi>(U.getUser()))
PhisToCheck.insert(MP);
U.set(NewDefTarget);
}
}
MSSA->removeFromLookups(MA);
MSSA->removeFromLists(MA);
if (!PhisToCheck.empty()) {
SmallVector<WeakVH, 16> PhisToOptimize{PhisToCheck.begin(),
PhisToCheck.end()};
PhisToCheck.clear();
unsigned PhisSize = PhisToOptimize.size();
while (PhisSize-- > 0)
if (MemoryPhi *MP =
cast_or_null<MemoryPhi>(PhisToOptimize.pop_back_val()))
tryRemoveTrivialPhi(MP);
}
}
void MemorySSAUpdater::removeBlocks(
const SmallSetVector<BasicBlock *, 8> &DeadBlocks) {
for (BasicBlock *BB : DeadBlocks) {
Instruction *TI = BB->getTerminator();
assert(TI && "Basic block expected to have a terminator instruction");
for (BasicBlock *Succ : successors(TI))
if (!DeadBlocks.count(Succ))
if (MemoryPhi *MP = MSSA->getMemoryAccess(Succ)) {
MP->unorderedDeleteIncomingBlock(BB);
tryRemoveTrivialPhi(MP);
}
if (MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB))
for (MemoryAccess &MA : *Acc)
MA.dropAllReferences();
}
for (BasicBlock *BB : DeadBlocks) {
MemorySSA::AccessList *Acc = MSSA->getWritableBlockAccesses(BB);
if (!Acc)
continue;
for (MemoryAccess &MA : llvm::make_early_inc_range(*Acc)) {
MSSA->removeFromLookups(&MA);
MSSA->removeFromLists(&MA);
}
}
}
void MemorySSAUpdater::tryRemoveTrivialPhis(ArrayRef<WeakVH> UpdatedPHIs) {
for (const auto &VH : UpdatedPHIs)
if (auto *MPhi = cast_or_null<MemoryPhi>(VH))
tryRemoveTrivialPhi(MPhi);
}
void MemorySSAUpdater::changeToUnreachable(const Instruction *I) {
const BasicBlock *BB = I->getParent();
auto BBI = I->getIterator(), BBE = BB->end();
while (BBI != BBE)
removeMemoryAccess(&*(BBI++));
SmallVector<WeakVH, 16> UpdatedPHIs;
for (const BasicBlock *Successor : successors(BB)) {
removeDuplicatePhiEdgesBetween(BB, Successor);
if (MemoryPhi *MPhi = MSSA->getMemoryAccess(Successor)) {
MPhi->unorderedDeleteIncomingBlock(BB);
UpdatedPHIs.push_back(MPhi);
}
}
tryRemoveTrivialPhis(UpdatedPHIs);
}
MemoryAccess *MemorySSAUpdater::createMemoryAccessInBB(
Instruction *I, MemoryAccess *Definition, const BasicBlock *BB,
MemorySSA::InsertionPlace Point) {
MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
MSSA->insertIntoListsForBlock(NewAccess, BB, Point);
return NewAccess;
}
MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessBefore(
Instruction *I, MemoryAccess *Definition, MemoryUseOrDef *InsertPt) {
assert(I->getParent() == InsertPt->getBlock() &&
"New and old access must be in the same block");
MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
InsertPt->getIterator());
return NewAccess;
}
MemoryUseOrDef *MemorySSAUpdater::createMemoryAccessAfter(
Instruction *I, MemoryAccess *Definition, MemoryAccess *InsertPt) {
assert(I->getParent() == InsertPt->getBlock() &&
"New and old access must be in the same block");
MemoryUseOrDef *NewAccess = MSSA->createDefinedAccess(I, Definition);
MSSA->insertIntoListsBefore(NewAccess, InsertPt->getBlock(),
++InsertPt->getIterator());
return NewAccess;
}