30 #include "llvm/Config/llvm-config.h" 60 #define DEBUG_TYPE "memoryssa" 73 "
Memory SSA Printer", false, false)
78 "will consider trying to walk past (default = 100)"));
99 OS <<
"; " << *MA <<
"\n";
105 OS <<
"; " << *MA <<
"\n";
118 class MemoryLocOrCall {
122 MemoryLocOrCall() =
default;
136 if (!isa<FenceInst>(Inst))
154 if (IsCall != Other.IsCall)
158 return Loc == Other.Loc;
160 if (CS.getCalledValue() != Other.CS.getCalledValue())
163 return CS.arg_size() == Other.CS.arg_size() &&
164 std::equal(CS.arg_begin(), CS.arg_end(), Other.CS.arg_begin());
195 MLOC.getCS().getCalledValue()));
197 for (
const Value *
Arg : MLOC.getCS().args())
202 static bool isEqual(
const MemoryLocOrCall &LHS,
const MemoryLocOrCall &RHS) {
218 bool VolatileClobber = MayClobber->
isVolatile();
220 if (VolatileUse && VolatileClobber)
236 return !(SeqCstUse || MayClobberIsAcquire);
241 struct ClobberAlias {
255 assert(DefInst &&
"Defining instruction not actually an instruction");
259 if (
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
267 switch (II->getIntrinsicID()) {
268 case Intrinsic::lifetime_start:
273 case Intrinsic::lifetime_end:
274 case Intrinsic::invariant_start:
275 case Intrinsic::invariant_end:
276 case Intrinsic::assume:
289 if (
auto *DefLoad = dyn_cast<LoadInst>(DefInst))
290 if (
auto *UseLoad = dyn_cast<LoadInst>(UseInst))
300 const MemoryLocOrCall &UseMLOC,
319 struct UpwardsMemoryQuery {
331 UpwardsMemoryQuery() =
default;
346 switch (II->getIntrinsicID()) {
347 case Intrinsic::lifetime_end:
381 assert(MSSA.
dominates(ClobberAt, Start) &&
"Clobber doesn't dominate start?");
385 "liveOnEntry must clobber itself");
389 bool FoundClobber =
false;
395 while (!Worklist.
empty()) {
399 if (!VisitedPhis.
insert(MAP).second)
403 if (MA == ClobberAt) {
404 if (
auto *MD = dyn_cast<MemoryDef>(MA)) {
426 if (
auto *MD = dyn_cast<MemoryDef>(MA)) {
430 "Found clobber before reaching ClobberAt!");
434 assert(isa<MemoryPhi>(MA));
441 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
442 "ClobberAt never acted as a clobber");
449 class ClobberWalker {
465 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
469 : DefPath(Loc, Init, Init, Previous) {}
475 UpwardsMemoryQuery *
Query;
488 while ((Node = Node->
getIDom())) {
497 struct UpwardsWalkResult {
511 walkToPhiOrClobber(DefPath &Desc,
513 assert(!isa<MemoryUse>(Desc.Last) &&
"Uses don't exist in my world");
517 if (Current == StopAt)
520 if (
auto *MD = dyn_cast<MemoryDef>(Current)) {
526 return {MD,
true, CA.AR};
530 assert(isa<MemoryPhi>(Desc.Last) &&
531 "Ended at a non-clobber that's not a phi?");
532 return {Desc.Last,
false,
MayAlias};
536 ListIndex PriorNode) {
548 struct TerminatedPath {
566 assert(!PausedSearches.
empty() &&
"No searches to continue?");
570 while (!PausedSearches.
empty()) {
572 DefPath &Node = Paths[PathIndex];
592 if (!VisitedPhis.
insert({Node.Last, Node.Loc}).second)
595 UpwardsWalkResult Res = walkToPhiOrClobber(Node, StopWhere);
596 if (Res.IsKnownClobber) {
597 assert(Res.Result != StopWhere);
600 TerminatedPath Term{Res.Result, PathIndex};
601 if (!MSSA.
dominates(Res.Result, StopWhere))
609 if (Res.Result == StopWhere) {
617 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
623 template <
typename T,
typename Walker>
624 struct generic_def_path_iterator
626 std::forward_iterator_tag, T *> {
627 generic_def_path_iterator() =
default;
628 generic_def_path_iterator(Walker *
W, ListIndex
N) :
W(W),
N(N) {}
632 generic_def_path_iterator &operator++() {
633 N = curNode().Previous;
637 bool operator==(
const generic_def_path_iterator &
O)
const {
638 if (N.hasValue() != O.N.hasValue())
640 return !N.hasValue() || *N == *O.N;
644 T &curNode()
const {
return W->Paths[*
N]; }
650 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
651 using const_def_path_iterator =
652 generic_def_path_iterator<const DefPath, const ClobberWalker>;
655 return make_range(def_path_iterator(
this, From), def_path_iterator());
659 return make_range(const_def_path_iterator(
this, From),
660 const_def_path_iterator());
665 TerminatedPath PrimaryClobber;
671 ListIndex defPathIndex(
const DefPath &
N)
const {
673 const DefPath *NP = &
N;
675 "Out of bounds DefPath!");
676 return NP - &Paths.
front();
695 "Reset the optimization state.");
700 auto PriorPathsSize = Paths.
size();
706 addSearches(Phi, PausedSearches, 0);
712 auto Dom = Paths.
begin();
713 for (
auto I = std::next(Dom),
E = Paths.
end();
I !=
E; ++
I)
714 if (!MSSA.
dominates(
I->Clobber, Dom->Clobber))
716 auto Last = Paths.
end() - 1;
718 std::iter_swap(Last, Dom);
724 "liveOnEntry wasn't treated as a clobber?");
726 const auto *
Target = getWalkTarget(Current);
729 assert(
all_of(TerminatedPaths, [&](
const TerminatedPath &
P) {
730 return MSSA.
dominates(P.Clobber, Target);
737 Target, PausedSearches, NewPaused, TerminatedPaths)) {
741 auto Iter =
find_if(def_path(Blocker->LastNode), [&](
const DefPath &N) {
742 return defPathIndex(N) < PriorPathsSize;
744 assert(Iter != def_path_iterator());
746 DefPath &CurNode = *Iter;
747 assert(CurNode.Last == Current);
774 TerminatedPath
Result{CurNode.Last, defPathIndex(CurNode)};
781 if (NewPaused.
empty()) {
782 MoveDominatedPathToEnd(TerminatedPaths);
784 return {Result, std::move(TerminatedPaths)};
789 for (ListIndex Paused : NewPaused) {
790 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
791 if (WR.IsKnownClobber)
795 DefChainEnd = WR.Result;
798 if (!TerminatedPaths.
empty()) {
802 for (
auto *MA :
def_chain(const_cast<MemoryAccess *>(Target)))
808 for (
const TerminatedPath &TP : TerminatedPaths) {
811 if (DT.
dominates(ChainBB, TP.Clobber->getBlock()))
818 if (!Clobbers.
empty()) {
819 MoveDominatedPathToEnd(Clobbers);
821 return {Result, std::move(Clobbers)};
825 [&](ListIndex
I) {
return Paths[
I].Last == DefChainEnd; }));
828 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
830 PriorPathsSize = Paths.
size();
831 PausedSearches.
clear();
832 for (ListIndex I : NewPaused)
833 addSearches(DefChainPhi, PausedSearches, I);
836 Current = DefChainPhi;
840 void verifyOptResult(
const OptznResult &R)
const {
841 assert(
all_of(R.OtherClobbers, [&](
const TerminatedPath &
P) {
842 return MSSA.dominates(P.Clobber, R.PrimaryClobber.Clobber);
846 void resetPhiOptznState() {
853 : MSSA(MSSA), AA(AA), DT(DT) {}
863 if (
auto *MU = dyn_cast<MemoryUse>(Start))
864 Current = MU->getDefiningAccess();
866 DefPath FirstDesc(Q.StartingLoc, Current, Current,
None);
869 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
871 if (WalkResult.IsKnownClobber) {
872 Result = WalkResult.Result;
873 Q.AR = WalkResult.AR;
875 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
876 Current, Q.StartingLoc);
877 verifyOptResult(OptRes);
878 resetPhiOptznState();
879 Result = OptRes.PrimaryClobber.Clobber;
882 #ifdef EXPENSIVE_CHECKS 891 struct RenamePassData {
898 : DTN(D), ChildIt(It), IncomingVal(M) {}
900 void swap(RenamePassData &RHS) {
915 ClobberWalker Walker;
939 bool RenameAllUses) {
942 auto It = PerBlockAccesses.find(S);
944 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
947 auto *Phi = cast<MemoryPhi>(&Accesses->front());
949 int PhiIndex = Phi->getBasicBlockIndex(BB);
950 assert(PhiIndex != -1 &&
"Incomplete phi during partial rename");
951 Phi->setIncomingValue(PhiIndex, IncomingVal);
953 Phi->addIncoming(IncomingVal, BB);
961 bool RenameAllUses) {
962 auto It = PerBlockAccesses.find(BB);
964 if (It != PerBlockAccesses.end()) {
968 if (MUD->getDefiningAccess() ==
nullptr || RenameAllUses)
969 MUD->setDefiningAccess(IncomingVal);
970 if (isa<MemoryDef>(&L))
986 bool SkipVisited,
bool RenameAllUses) {
992 if (SkipVisited && AlreadyVisited)
995 IncomingVal = renameBlock(Root->
getBlock(), IncomingVal, RenameAllUses);
996 renameSuccessorPhis(Root->
getBlock(), IncomingVal, RenameAllUses);
999 while (!WorkStack.
empty()) {
1002 IncomingVal = WorkStack.
back().IncomingVal;
1004 if (ChildIt == Node->
end()) {
1008 ++WorkStack.
back().ChildIt;
1012 AlreadyVisited = !Visited.
insert(BB).second;
1013 if (SkipVisited && AlreadyVisited) {
1019 if (
auto *BlockDefs = getWritableBlockDefs(BB))
1020 IncomingVal = &*BlockDefs->rbegin();
1022 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
1023 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
1032 void MemorySSA::markUnreachableAsLiveOnEntry(
BasicBlock *BB) {
1033 assert(!DT->isReachableFromEntry(BB) &&
1034 "Reachable block found while handling unreachable blocks");
1041 if (!DT->isReachableFromEntry(S))
1043 auto It = PerBlockAccesses.find(S);
1045 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
1048 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1049 Phi->addIncoming(LiveOnEntryDef.get(), BB);
1052 auto It = PerBlockAccesses.find(BB);
1053 if (It == PerBlockAccesses.end())
1056 auto &Accesses = It->second;
1057 for (
auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1058 auto Next = std::next(AI);
1061 if (
auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1062 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1064 Accesses->erase(AI);
1070 : AA(AA), DT(DT),
F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1077 for (
const auto &Pair : PerBlockAccesses)
1083 auto Res = PerBlockAccesses.
insert(std::make_pair(BB,
nullptr));
1086 Res.first->second = llvm::make_unique<AccessList>();
1087 return Res.first->second.get();
1091 auto Res = PerBlockDefs.
insert(std::make_pair(BB,
nullptr));
1094 Res.first->second = llvm::make_unique<DefsList>();
1095 return Res.first->second.get();
1111 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1115 void optimizeUses();
1119 struct MemlocStackInfo {
1122 unsigned long StackEpoch;
1123 unsigned long PopEpoch;
1128 unsigned long LowerBound;
1131 unsigned long LastKill;
1136 void optimizeUsesInBlock(
const BasicBlock *,
unsigned long &,
unsigned long &,
1160 void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1161 const BasicBlock *BB,
unsigned long &StackEpoch,
unsigned long &PopEpoch,
1167 if (Accesses ==
nullptr)
1174 !VersionStack.
empty() &&
1175 "Version stack should have liveOnEntry sentinel dominating everything");
1177 if (DT->dominates(BackBlock, BB))
1193 MU->setDefiningAccess(MSSA->getLiveOnEntryDef(),
true,
None);
1197 MemoryLocOrCall UseMLOC(MU);
1198 auto &LocInfo = LocStackInfo[UseMLOC];
1202 if (LocInfo.PopEpoch != PopEpoch) {
1203 LocInfo.PopEpoch = PopEpoch;
1204 LocInfo.StackEpoch = StackEpoch;
1216 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1217 !DT->dominates(LocInfo.LowerBoundBlock, BB)) {
1221 LocInfo.LowerBound = 0;
1222 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1223 LocInfo.LastKillValid =
false;
1225 }
else if (LocInfo.StackEpoch != StackEpoch) {
1229 LocInfo.PopEpoch = PopEpoch;
1230 LocInfo.StackEpoch = StackEpoch;
1232 if (!LocInfo.LastKillValid) {
1233 LocInfo.LastKill = VersionStack.
size() - 1;
1234 LocInfo.LastKillValid =
true;
1240 assert(LocInfo.LowerBound < VersionStack.
size() &&
1241 "Lower bound out of range");
1242 assert(LocInfo.LastKill < VersionStack.
size() &&
1243 "Last kill info out of range");
1245 unsigned long UpperBound = VersionStack.
size() - 1;
1248 LLVM_DEBUG(
dbgs() <<
"MemorySSA skipping optimization of " << *MU <<
" (" 1249 << *(MU->getMemoryInst()) <<
")" 1250 <<
" because there are " 1251 << UpperBound - LocInfo.LowerBound
1252 <<
" stores to disambiguate\n");
1255 LocInfo.LastKillValid =
false;
1258 bool FoundClobberResult =
false;
1259 while (UpperBound > LocInfo.LowerBound) {
1260 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1265 while (VersionStack[UpperBound] != Result) {
1269 FoundClobberResult =
true;
1273 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1276 if (!UseMLOC.IsCall &&
lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1279 FoundClobberResult =
true;
1285 FoundClobberResult =
true;
1296 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1298 if (MSSA->isLiveOnEntryDef(VersionStack[UpperBound]))
1300 MU->setDefiningAccess(VersionStack[UpperBound],
true, LocInfo.AR);
1301 LocInfo.LastKill = UpperBound;
1305 MU->setDefiningAccess(VersionStack[LocInfo.LastKill],
true, LocInfo.AR);
1307 LocInfo.LowerBound = VersionStack.
size() - 1;
1308 LocInfo.LowerBoundBlock = BB;
1316 VersionStack.
push_back(MSSA->getLiveOnEntryDef());
1318 unsigned long StackEpoch = 1;
1319 unsigned long PopEpoch = 1;
1321 for (
const auto *DomNode :
depth_first(DT->getRootNode()))
1322 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1326 void MemorySSA::placePHINodes(
1335 for (
auto &BB : IDFBlocks)
1336 createMemoryPhi(BB);
1339 void MemorySSA::buildMemorySSA() {
1347 LiveOnEntryDef.reset(
new MemoryDef(
F.getContext(),
nullptr,
nullptr,
1348 &StartingPoint, NextID++));
1357 bool InsertIntoDef =
false;
1366 Accesses = getOrCreateAccessList(&B);
1368 if (isa<MemoryDef>(MUD)) {
1369 InsertIntoDef =
true;
1371 Defs = getOrCreateDefsList(&B);
1376 DefiningBlocks.
insert(&B);
1378 placePHINodes(DefiningBlocks);
1383 renamePass(DT->getRootNode(), LiveOnEntryDef.get(), Visited);
1392 if (!Visited.
count(&BB))
1393 markUnreachableAsLiveOnEntry(&BB);
1400 return Walker.get();
1402 Walker = llvm::make_unique<CachingWalker>(
this, AA, DT);
1403 return Walker.get();
1412 auto *Accesses = getOrCreateAccessList(BB);
1416 if (isa<MemoryPhi>(NewAccess)) {
1417 Accesses->push_front(NewAccess);
1418 auto *Defs = getOrCreateDefsList(BB);
1419 Defs->push_front(*NewAccess);
1422 *Accesses, [](
const MemoryAccess &MA) {
return isa<MemoryPhi>(MA); });
1423 Accesses->insert(AI, NewAccess);
1424 if (!isa<MemoryUse>(NewAccess)) {
1425 auto *Defs = getOrCreateDefsList(BB);
1427 *Defs, [](
const MemoryAccess &MA) {
return isa<MemoryPhi>(MA); });
1428 Defs->insert(DI, *NewAccess);
1432 Accesses->push_back(NewAccess);
1433 if (!isa<MemoryUse>(NewAccess)) {
1434 auto *Defs = getOrCreateDefsList(BB);
1435 Defs->push_back(*NewAccess);
1438 BlockNumberingValid.erase(BB);
1444 bool WasEnd = InsertPt == Accesses->end();
1446 if (!isa<MemoryUse>(What)) {
1447 auto *Defs = getOrCreateDefsList(BB);
1453 Defs->push_back(*What);
1454 }
else if (isa<MemoryDef>(InsertPt)) {
1455 Defs->insert(InsertPt->getDefsIterator(), *What);
1457 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1460 if (InsertPt == Accesses->end())
1461 Defs->push_back(*What);
1463 Defs->insert(InsertPt->getDefsIterator(), *What);
1466 BlockNumberingValid.erase(BB);
1483 if (isa<MemoryPhi>(What)) {
1485 "Can only move a Phi at the beginning of the block");
1487 ValueToMemoryAccess.erase(What->
getBlock());
1488 bool Inserted = ValueToMemoryAccess.insert({BB, What}).
second;
1490 assert(Inserted &&
"Cannot move a Phi to a block that already has one");
1503 ValueToMemoryAccess[BB] = Phi;
1509 assert(!isa<PHINode>(I) &&
"Cannot create a defined access for a PHI");
1512 NewAccess !=
nullptr &&
1513 "Tried to create a memory access for a non-memory touching instruction");
1522 if (
auto *
SI = dyn_cast<StoreInst>(I)) {
1523 if (!
SI->isUnordered())
1525 }
else if (
auto *LI = dyn_cast<LoadInst>(I)) {
1526 if (!LI->isUnordered())
1539 if (II->getIntrinsicID() == Intrinsic::assume)
1565 ValueToMemoryAccess[
I] = MUD;
1570 bool MemorySSA::dominatesUse(
const MemoryAccess *Replacer,
1572 if (isa<MemoryUseOrDef>(Replacee))
1574 const auto *MP = cast<MemoryPhi>(Replacee);
1578 for (
const Use &
Arg : MP->operands()) {
1579 if (
Arg.get() != Replacee &&
1580 !DT->dominates(Replacer->
getBlock(), MP->getIncomingBlock(
Arg)))
1589 "Trying to remove memory access that still has uses");
1590 BlockNumbering.erase(MA);
1591 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1592 MUD->setDefiningAccess(
nullptr);
1594 if (!isa<MemoryUse>(MA))
1595 Walker->invalidateInfo(MA);
1598 if (
const auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1599 MemoryInst = MUD->getMemoryInst();
1603 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1604 if (VMA->second == MA)
1605 ValueToMemoryAccess.erase(VMA);
1618 if (!isa<MemoryUse>(MA)) {
1619 auto DefsIt = PerBlockDefs.find(BB);
1620 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1623 PerBlockDefs.erase(DefsIt);
1628 auto AccessIt = PerBlockAccesses.find(BB);
1629 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
1631 Accesses->erase(MA);
1633 Accesses->remove(MA);
1635 if (Accesses->empty()) {
1636 PerBlockAccesses.erase(AccessIt);
1637 BlockNumberingValid.erase(BB);
1643 F.print(OS, &Writer);
1646 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1655 Walker->verify(
this);
1662 if (BlockNumberingValid.empty())
1667 if (!ValidBlocks.
count(&BB))
1670 ValidBlocks.
erase(&BB);
1678 unsigned long LastNumber = 0;
1680 auto ThisNumberIter = BlockNumbering.find(&MA);
1681 assert(ThisNumberIter != BlockNumbering.end() &&
1682 "MemoryAccess has no domination number in a valid block!");
1684 unsigned long ThisNumber = ThisNumberIter->second;
1685 assert(ThisNumber > LastNumber &&
1686 "Domination numbers should be strictly increasing!");
1687 LastNumber = ThisNumber;
1692 "All valid BasicBlocks should exist in F -- dangling pointers?");
1715 assert((!MA || (AL && (isa<MemoryUse>(MA) || DL))) &&
1716 "We have memory affecting instructions " 1717 "in this block but they are not in the " 1718 "access list or defs list");
1721 if (isa<MemoryDef>(MA))
1730 assert(AL->size() == ActualAccesses.
size() &&
1731 "We don't have the same number of accesses in the block as on the " 1734 "Either we should have a defs list, or we should have no defs");
1735 assert((!DL || DL->size() == ActualDefs.
size()) &&
1736 "We don't have the same number of defs in the block as on the " 1738 auto ALI = AL->begin();
1739 auto AAI = ActualAccesses.
begin();
1740 while (ALI != AL->end() && AAI != ActualAccesses.
end()) {
1741 assert(&*ALI == *AAI &&
"Not the same accesses in the same order");
1745 ActualAccesses.
clear();
1747 auto DLI = DL->begin();
1748 auto ADI = ActualDefs.
begin();
1749 while (DLI != DL->end() && ADI != ActualDefs.
end()) {
1750 assert(&*DLI == *ADI &&
"Not the same defs in the same order");
1766 for (
const Use &U : MP->
uses())
1774 for (
const Use &U : MD->
uses())
1788 "Null def but use not point to live on entry def");
1791 "Did not find use in def's use list");
1802 assert(Phi->getNumOperands() ==
static_cast<unsigned>(std::distance(
1804 "Incomplete MemoryPhi Node");
1805 for (
unsigned I = 0,
E = Phi->getNumIncomingValues(); I !=
E; ++
I) {
1806 verifyUseInDefs(Phi->getIncomingValue(I), Phi);
1809 "Incoming phi block not a block predecessor");
1815 verifyUseInDefs(MA->getDefiningAccess(), MA);
1822 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
1826 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
1835 void MemorySSA::renumberBlock(
const BasicBlock *
B)
const {
1837 unsigned long CurrentNumber = 0;
1839 assert(AL !=
nullptr &&
"Asking to renumber an empty block");
1840 for (
const auto &I : *AL)
1841 BlockNumbering[&
I] = ++CurrentNumber;
1842 BlockNumberingValid.insert(B);
1853 "Asking for local domination when accesses are in different blocks!");
1855 if (Dominatee == Dominator)
1868 if (!BlockNumberingValid.count(DominatorBlock))
1869 renumberBlock(DominatorBlock);
1871 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1873 assert(DominatorNum != 0 &&
"Block was not numbered properly");
1874 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1875 assert(DominateeNum != 0 &&
"Block was not numbered properly");
1876 return DominatorNum < DominateeNum;
1881 if (Dominator == Dominatee)
1893 const Use &Dominatee)
const {
1895 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1897 if (UseBB != Dominator->
getBlock())
1898 return DT->dominates(Dominator->
getBlock(), UseBB);
1909 switch (getValueID()) {
1910 case MemoryPhiVal:
return static_cast<const MemoryPhi *
>(
this)->
print(OS);
1911 case MemoryDefVal:
return static_cast<const MemoryDef *
>(
this)->
print(OS);
1912 case MemoryUseVal:
return static_cast<const MemoryUse *
>(
this)->
print(OS);
1921 if (A && A->getID())
1927 OS <<
getID() <<
" = MemoryDef(";
1931 if (isOptimized()) {
1933 printID(getOptimized());
1942 OS <<
getID() <<
" = MemoryPhi(";
1943 for (
const auto &
Op : operands()) {
1957 if (
unsigned ID = MA->
getID())
1969 if (UO && UO->
getID())
1981 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1999 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
2002 MSSA.verifyMemorySSA();
2017 OS <<
"MemorySSA for function: " << F.
getName() <<
"\n";
2045 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2046 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
2064 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
2065 MUD->resetOptimized();
2072 MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
2074 return Walker.findClobber(StartingAccess, Q);
2079 if (isa<MemoryPhi>(StartingAccess))
2080 return StartingAccess;
2082 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
2084 return StartingUseOrDef;
2086 Instruction *I = StartingUseOrDef->getMemoryInst();
2091 return StartingUseOrDef;
2093 UpwardsMemoryQuery Q;
2094 Q.OriginalAccess = StartingUseOrDef;
2095 Q.StartingLoc = Loc;
2101 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
2102 ? StartingUseOrDef->getDefiningAccess()
2105 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
2106 LLVM_DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *I <<
" is ");
2108 LLVM_DEBUG(
dbgs() <<
"Final Memory SSA clobber for " << *I <<
" is ");
2117 if (!StartingAccess)
2123 if (StartingAccess->isOptimized())
2124 return StartingAccess->getOptimized();
2126 const Instruction *I = StartingAccess->getMemoryInst();
2127 UpwardsMemoryQuery Q(I, StartingAccess);
2132 return StartingAccess;
2136 StartingAccess->setOptimized(LiveOnEntry);
2137 StartingAccess->setOptimizedAccessType(
None);
2142 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2147 StartingAccess->setOptimized(DefiningAccess);
2148 StartingAccess->setOptimizedAccessType(
None);
2149 return DefiningAccess;
2153 LLVM_DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *I <<
" is ");
2155 LLVM_DEBUG(
dbgs() <<
"Final Memory SSA clobber for " << *I <<
" is ");
2158 StartingAccess->setOptimized(Result);
2160 StartingAccess->setOptimizedAccessType(
None);
2162 StartingAccess->setOptimizedAccessType(
MustAlias);
2169 if (
auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2170 return Use->getDefiningAccess();
2176 if (
auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2177 return Use->getDefiningAccess();
2178 return StartingAccess;
MemorySSAWalker * getWalker()
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
The access may reference and may modify the value stored in memory.
void initializeMemorySSAWrapperPassPass(PassRegistry &)
void push_back(const T &Elt)
AccessList * getWritableBlockAccesses(const BasicBlock *BB) const
typename std::vector< DomTreeNodeBase *>::const_iterator const_iterator
Safe Stack instrumentation pass
iterator_range< use_iterator > uses()
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
Value * getPointerOperand(Value *V)
A helper function that returns the pointer operand of a load, store or GEP instruction.
virtual void verify(const MemorySSA *MSSA)
void dropAllReferences()
Drop all references to operands.
Atomic ordering constants.
MemorySSAPrinterLegacyPass()
bool isFenceLike() const
Return true if this instruction behaves like a memory fence: it can load or store to memory location ...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
void print(raw_ostream &OS) const
Compute iterated dominance frontiers using a linear time algorithm.
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
A Module instance is used to store all the information related to an LLVM module. ...
void push_back(reference Node)
Insert a node at the back; never copies.
This class provides various memory handling functions that manipulate MemoryBlock instances...
Implements a dense probed hash-table based set.
MemoryUseOrDef * createDefinedAccess(Instruction *, MemoryAccess *)
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
The two locations do not alias at all.
Extension point for the Value hierarchy.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
static const char LiveOnEntryStr[]
LLVMContext & getContext() const
All values hold a context through their type.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass which computes a DominatorTree.
OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA, DominatorTree *DT)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
block Block Frequency true
An instruction for reading from memory.
This defines the Use class.
void print(raw_ostream &OS) const
MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
LLVMContext & getContext() const
Get the context in which this basic block lives.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass, "memoryssa", "Memory SSA", false, true) INITIALIZE_PASS_END(MemorySSAWrapperPass
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
Represents read-only accesses to memory.
AliasResult alias(const MemoryLocation &LocA, const MemoryLocation &LocB)
The main low level interface to the alias analysis implementation.
This class is a batch walker of all MemoryUse's in the program, and points their defining access at t...
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock *> &Visited)
A MemorySSAWalker that does AA walks to disambiguate accesses.
A Use represents the edge between a Value definition and its users.
void setDefiningBlocks(const SmallPtrSetImpl< BasicBlock *> &Blocks)
Give the IDF calculator the set of blocks in which the value is defined.
static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
MemorySSAAnnotatedWriter(const MemorySSA *M)
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
Encapsulates MemorySSA, including all data associated with memory accesses.
const DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, InsertionPlace)
static void LLVM_ATTRIBUTE_UNUSED checkClobberSanity(MemoryAccess *Start, MemoryAccess *ClobberAt, const MemoryLocation &StartLoc, const MemorySSA &MSSA, const UpwardsMemoryQuery &Query, AliasAnalysis &AA)
Verifies that Start is clobbered by ClobberAt, and that nothing inbetween Start and ClobberAt can clo...
static bool isOrdered(const Instruction *I)
APInt operator*(APInt a, uint64_t RHS)
void verifyDefUses(Function &F) const
Verify the immediate use information, by walking all the memory accesses and verifying that...
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
A simple intrusive list implementation.
static ClobberAlias instructionClobbersQuery(MemoryDef *MD, const MemoryLocation &UseLoc, const Instruction *UseInst, AliasAnalysis &AA)
LLVM_NODISCARD bool isMustSet(const ModRefInfo MRI)
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
ppc ctr loops PowerPC CTR Loops Verify
static int getID(struct InternalInstruction *insn, const void *miiArg)
upward_defs_iterator upward_defs_end()
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
void emitBasicBlockStartAnnot(const BasicBlock *BB, formatted_raw_ostream &OS) override
emitBasicBlockStartAnnot - This may be implemented to emit a string right after the basic block label...
This is the generic walker interface for walkers of MemorySSA.
CRTP base class which implements the entire standard iterator facade in terms of a minimal subset of ...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static bool lifetimeEndsAt(MemoryDef *MD, const MemoryLocation &Loc, AliasAnalysis &AA)
bool isAtLeastOrStrongerThan(AtomicOrdering ao, AtomicOrdering other)
bool pointsToConstantMemory(const MemoryLocation &Loc, bool OrLocal=false)
Checks whether the given location points to constant memory, or if OrLocal is true whether it points ...
An assembly annotator class to print Memory SSA information in comments.
void removeFromLookups(MemoryAccess *)
Properly remove MA from all of MemorySSA's lookup tables.
static MemoryLocation get(const LoadInst *LI)
Return a location with information about the memory reference by the given instruction.
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
static bool isEqual(const MemoryLocOrCall &LHS, const MemoryLocOrCall &RHS)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
early cse Early CSE w MemorySSA
Interval::pred_iterator pred_begin(Interval *I)
pred_begin/pred_end - define methods so that Intervals may be used just like BasicBlocks can with the...
InsertionPlace
Used in various insertion functions to specify whether we are talking about the beginning or end of a...
Represent the analysis usage information of a pass.
void print(raw_ostream &OS) const
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
void verifyDomination(Function &F) const
Verify the domination properties of MemorySSA by checking that each definition dominates all of its u...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
Memory true print Memory SSA Printer
void invalidateInfo(MemoryAccess *) override
Given a memory access, invalidate anything this walker knows about that access.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
An intrusive list with ownership and callbacks specified/controlled by ilist_traits, only with API safe for polymorphic types.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
Memory true print Memory SSA static false cl::opt< unsigned > MaxCheckLimit("memssa-check-limit", cl::Hidden, cl::init(100), cl::desc("The maximum number of stores/phis MemorySSA" "will consider trying to walk past (default = 100)"))
MemoryUseOrDef * getMemoryAccess(const Instruction *) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
void optimizeUses()
Optimize uses to point to their actual clobbering definitions.
The two locations may or may not alias. This is the least precise result.
Representation for a specific memory location.
The two locations precisely alias each other.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
void verifyOrdering(Function &F) const
Verify that the order and existence of MemoryAccesses matches the order and existence of memory affec...
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false, Optional< AliasResult > AR=MayAlias)
unsigned getNumOperands() const
base_list_type::iterator iterator
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
void calculate(SmallVectorImpl< BasicBlock *> &IDFBlocks)
Calculate iterated dominance frontiers.
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
BasicBlock * getBlock() const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
pred_range predecessors(BasicBlock *BB)
void verify(const MemorySSA *MSSA) override
void emitInstructionAnnot(const Instruction *I, formatted_raw_ostream &OS) override
emitInstructionAnnot - This may be implemented to emit a string right before an instruction is emitte...
MemoryAccess * getLiveOnEntryDef() const
void print(raw_ostream &OS) const
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
A range adaptor for a pair of iterators.
void removeFromLists(MemoryAccess *, bool ShouldDelete=true)
Properly remove MA from all of MemorySSA's lists.
Target - Wrapper for Target specific information.
void push_back(pointer val)
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Class that has the common methods + fields of memory uses/defs.
ModRefInfo getModRefInfo(ImmutableCallSite CS, const MemoryLocation &Loc)
getModRefInfo (for call sites) - Return information about whether a particular call site modifies or ...
void setPreservesAll()
Set by analyses that do not transform their input at all.
iterator_range< user_iterator > users()
bool isMustAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are must-alias.
An opaque object representing a hash code.
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
#define LLVM_ATTRIBUTE_UNUSED
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
amdgpu Simplify well known AMD library false Value Value * Arg
void initializeMemorySSAPrinterLegacyPassPass(PassRegistry &)
LLVM_NODISCARD bool isModSet(const ModRefInfo MRI)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
MemorySSAWalker(MemorySSA *)
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
void emplace_back(ArgTypes &&... Args)
LLVM_NODISCARD bool empty() const
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
This file provides utility analysis objects describing memory locations.
StringRef getName() const
Return a constant reference to the value's name.
Establish a view to a call site for examination.
CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *)
void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
static void Query(const MachineInstr &MI, AliasAnalysis &AA, bool &Read, bool &Write, bool &Effects, bool &StackPointer)
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
AnalysisUsage & addRequiredTransitive()
iterator_range< df_iterator< T > > depth_first(const T &G)
MemoryAccess * getClobberingMemoryAccess(const Instruction *I)
Given a memory Mod/Ref/ModRef'ing instruction, calling this will give you the nearest dominating Memo...
Determine the iterated dominance frontier, given a set of defining blocks, and optionally, a set of live-in blocks.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
static cl::opt< bool > VerifyMemorySSA("verify-memoryssa", cl::init(false), cl::Hidden, cl::desc("Verify MemorySSA in legacy printer pass."))
Result run(Function &F, FunctionAnalysisManager &AM)
static bool areLoadsReorderable(const LoadInst *Use, const LoadInst *MayClobber)
This does one-way checks to see if Use could theoretically be hoisted above MayClobber.
LLVM Value Representation.
static MemoryLocOrCall getTombstoneKey()
succ_range successors(BasicBlock *BB)
upward_defs_iterator upward_defs_begin(const MemoryAccessPair &Pair)
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
static bool isUseTriviallyOptimizableToLiveOnEntry(AliasAnalysis &AA, const Instruction *I)
This class implements an extremely fast bulk output stream that can only output to a stream...
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
static unsigned getHashValue(const MemoryLocOrCall &MLOC)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void setBlock(BasicBlock *BB)
Used by MemorySSA to change the block of a MemoryAccess when it is moved.
LLVM_NODISCARD bool isModOrRefSet(const ModRefInfo MRI)
bool operator==(uint64_t V1, const APInt &V2)
void verifyDominationNumbers(const Function &F) const
Verify that all of the blocks we believe to have valid domination numbers actually have valid dominat...
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
void print(raw_ostream &) const
This header defines various interfaces for pass management in LLVM.
static MemoryLocOrCall getEmptyKey()
void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, AccessList::iterator)
A special type used by analysis passes to provide an address that identifies that particular analysis...
reverse_iterator rbegin()
std::pair< MemoryAccess *, MemoryLocation > MemoryAccessPair
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.
LLVM_NODISCARD bool isRefSet(const ModRefInfo MRI)