44 #define DEBUG_TYPE "memoryssa"
57 "
Memory SSA Printer", false, false)
62 "will consider trying to walk past (default = 100)"));
81 OS <<
"; " << *MA <<
"\n";
87 OS <<
"; " << *MA <<
"\n";
98 class MemoryLocOrCall {
100 MemoryLocOrCall() : IsCall(
false) {}
102 : MemoryLocOrCall(MUD->getMemoryInst()) {}
104 : MemoryLocOrCall(MUD->getMemoryInst()) {}
114 if (!isa<FenceInst>(Inst))
120 : IsCall(
false), Loc(Loc) {}
132 bool operator==(
const MemoryLocOrCall &Other)
const {
133 if (IsCall != Other.IsCall)
137 return CS.getCalledValue() == Other.CS.getCalledValue();
138 return Loc == Other.Loc;
161 MLOC.getCS().getCalledValue()));
165 static bool isEqual(
const MemoryLocOrCall &LHS,
const MemoryLocOrCall &RHS) {
181 bool VolatileClobber = MayClobber->
isVolatile();
183 if (VolatileUse && VolatileClobber)
205 if (SeqCstUse || MayClobberIsAcquire)
215 assert(DefInst &&
"Defining instruction not actually an instruction");
218 if (
const IntrinsicInst *II = dyn_cast<IntrinsicInst>(DefInst)) {
221 switch (II->getIntrinsicID()) {
222 case Intrinsic::lifetime_start:
226 case Intrinsic::lifetime_end:
227 case Intrinsic::invariant_start:
228 case Intrinsic::invariant_end:
229 case Intrinsic::assume:
241 if (
auto *DefLoad = dyn_cast<LoadInst>(DefInst)) {
242 if (
auto *UseLoad = dyn_cast<LoadInst>(UseInst)) {
258 const MemoryLocOrCall &UseMLOC,
277 struct UpwardsMemoryQuery {
289 : IsCall(
false), Inst(nullptr), OriginalAccess(nullptr) {}
294 StartingLoc = MemoryLocation::get(Inst);
302 switch (II->getIntrinsicID()) {
303 case Intrinsic::lifetime_end:
312 static bool isUseTriviallyOptimizableToLiveOnEntry(
AliasAnalysis &AA,
319 return isa<LoadInst>(
I) && (I->
getMetadata(LLVMContext::MD_invariant_load) ||
340 assert(MSSA.
dominates(ClobberAt, Start) &&
"Clobber doesn't dominate start?");
344 "liveOnEntry must clobber itself");
348 bool FoundClobber =
false;
354 while (!Worklist.
empty()) {
358 if (!VisitedPhis.
insert(MAP).second)
362 if (MA == ClobberAt) {
363 if (
auto *MD = dyn_cast<MemoryDef>(MA)) {
379 if (
auto *MD = dyn_cast<MemoryDef>(MA)) {
382 "Found clobber before reaching ClobberAt!");
386 assert(isa<MemoryPhi>(MA));
393 assert((isa<MemoryPhi>(ClobberAt) || FoundClobber) &&
394 "ClobberAt never acted as a clobber");
399 class ClobberWalker {
415 : Loc(Loc), First(First), Last(Last), Previous(Previous) {}
419 : DefPath(Loc, Init, Init, Previous) {}
425 UpwardsMemoryQuery *
Query;
438 while ((Node = Node->
getIDom())) {
447 struct UpwardsWalkResult {
460 walkToPhiOrClobber(DefPath &
Desc,
462 assert(!isa<MemoryUse>(Desc.Last) &&
"Uses don't exist in my world");
466 if (Current == StopAt)
467 return {Current,
false};
469 if (
auto *MD = dyn_cast<MemoryDef>(Current))
475 assert(isa<MemoryPhi>(Desc.Last) &&
476 "Ended at a non-clobber that's not a phi?");
477 return {Desc.Last,
false};
481 ListIndex PriorNode) {
486 Paths.emplace_back(
P.second,
P.first, PriorNode);
493 struct TerminatedPath {
511 assert(!PausedSearches.
empty() &&
"No searches to continue?");
515 while (!PausedSearches.
empty()) {
517 DefPath &Node = Paths[PathIndex];
540 UpwardsWalkResult Res = walkToPhiOrClobber(Node, StopWhere);
541 if (Res.IsKnownClobber) {
542 assert(Res.Result != StopWhere);
545 TerminatedPath Term{Res.Result, PathIndex};
546 if (!MSSA.
dominates(Res.Result, StopWhere))
554 if (Res.Result == StopWhere) {
562 addSearches(cast<MemoryPhi>(Res.Result), PausedSearches, PathIndex);
568 template <
typename T,
typename Walker>
569 struct generic_def_path_iterator
571 std::forward_iterator_tag, T *> {
572 generic_def_path_iterator() : W(nullptr),
N(
None) {}
573 generic_def_path_iterator(Walker *W, ListIndex
N) : W(W), N(N) {}
578 N = curNode().Previous;
582 bool operator==(
const generic_def_path_iterator &O)
const {
583 if (
N.hasValue() != O.N.hasValue())
585 return !
N.hasValue() || *
N == *O.N;
589 T &curNode()
const {
return W->Paths[*
N]; }
595 using def_path_iterator = generic_def_path_iterator<DefPath, ClobberWalker>;
596 using const_def_path_iterator =
597 generic_def_path_iterator<const DefPath, const ClobberWalker>;
600 return make_range(def_path_iterator(
this, From), def_path_iterator());
604 return make_range(const_def_path_iterator(
this, From),
605 const_def_path_iterator());
610 TerminatedPath PrimaryClobber;
616 ListIndex defPathIndex(
const DefPath &
N)
const {
618 const DefPath *NP = &
N;
619 assert(!Paths.empty() && NP >= &Paths.front() && NP <= &Paths.back() &&
620 "Out of bounds DefPath!");
621 return NP - &Paths.front();
640 "Reset the optimization state.");
642 Paths.emplace_back(Loc, Start, Phi,
None);
645 auto PriorPathsSize = Paths.size();
651 addSearches(Phi, PausedSearches, 0);
656 assert(!Paths.empty() &&
"Need a path to move");
657 auto Dom = Paths.begin();
658 for (
auto I = std::next(Dom),
E = Paths.end(); I !=
E; ++
I)
659 if (!MSSA.
dominates(I->Clobber, Dom->Clobber))
661 auto Last = Paths.end() - 1;
663 std::iter_swap(Last, Dom);
669 "liveOnEntry wasn't treated as a clobber?");
671 const auto *
Target = getWalkTarget(Current);
674 assert(
all_of(TerminatedPaths, [&](
const TerminatedPath &
P) {
675 return MSSA.
dominates(P.Clobber, Target);
682 Target, PausedSearches, NewPaused, TerminatedPaths)) {
686 auto Iter =
find_if(def_path(Blocker->LastNode), [&](
const DefPath &N) {
687 return defPathIndex(N) < PriorPathsSize;
689 assert(Iter != def_path_iterator());
691 DefPath &CurNode = *Iter;
692 assert(CurNode.Last == Current);
719 TerminatedPath Result{CurNode.Last, defPathIndex(CurNode)};
726 if (NewPaused.
empty()) {
727 MoveDominatedPathToEnd(TerminatedPaths);
729 return {Result, std::move(TerminatedPaths)};
734 for (ListIndex Paused : NewPaused) {
735 UpwardsWalkResult WR = walkToPhiOrClobber(Paths[Paused]);
736 if (WR.IsKnownClobber)
740 DefChainEnd = WR.Result;
743 if (!TerminatedPaths.
empty()) {
747 for (
auto *MA :
def_chain(const_cast<MemoryAccess *>(Target)))
753 for (
const TerminatedPath &TP : TerminatedPaths) {
756 if (DT.dominates(ChainBB, TP.Clobber->getBlock()))
763 if (!Clobbers.
empty()) {
764 MoveDominatedPathToEnd(Clobbers);
766 return {Result, std::move(Clobbers)};
770 [&](ListIndex I) {
return Paths[
I].Last == DefChainEnd; }));
773 auto *DefChainPhi = cast<MemoryPhi>(DefChainEnd);
775 PriorPathsSize = Paths.size();
776 PausedSearches.
clear();
777 for (ListIndex I : NewPaused)
778 addSearches(DefChainPhi, PausedSearches, I);
781 Current = DefChainPhi;
785 void verifyOptResult(
const OptznResult &R)
const {
786 assert(
all_of(R.OtherClobbers, [&](
const TerminatedPath &P) {
787 return MSSA.
dominates(P.Clobber, R.PrimaryClobber.Clobber);
791 void resetPhiOptznState() {
798 : MSSA(MSSA), AA(AA), DT(DT) {}
810 if (
auto *MU = dyn_cast<MemoryUse>(Start))
811 Current = MU->getDefiningAccess();
813 DefPath FirstDesc(Q.StartingLoc, Current, Current,
None);
816 UpwardsWalkResult WalkResult = walkToPhiOrClobber(FirstDesc);
818 if (WalkResult.IsKnownClobber) {
819 Result = WalkResult.Result;
821 OptznResult OptRes = tryOptimizePhi(cast<MemoryPhi>(FirstDesc.Last),
822 Current, Q.StartingLoc);
823 verifyOptResult(OptRes);
824 resetPhiOptznState();
825 Result = OptRes.PrimaryClobber.Clobber;
828 #ifdef EXPENSIVE_CHECKS
829 checkClobberSanity(Current, Result, Q.StartingLoc, MSSA, Q, AA);
837 struct RenamePassData {
844 : DTN(D), ChildIt(It), IncomingVal(M) {}
845 void swap(RenamePassData &RHS) {
858 ClobberWalker Walker;
859 bool AutoResetWalker;
888 bool RenameAllUses) {
891 auto It = PerBlockAccesses.find(S);
893 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
896 auto *Phi = cast<MemoryPhi>(&Accesses->front());
899 assert(PhiIndex != -1 &&
"Incomplete phi during partial rename");
910 bool RenameAllUses) {
911 auto It = PerBlockAccesses.find(BB);
913 if (It != PerBlockAccesses.end()) {
917 if (MUD->getDefiningAccess() ==
nullptr || RenameAllUses)
918 MUD->setDefiningAccess(IncomingVal);
919 if (isa<MemoryDef>(&
L))
935 bool SkipVisited,
bool RenameAllUses) {
941 if (SkipVisited && AlreadyVisited)
944 IncomingVal = renameBlock(Root->
getBlock(), IncomingVal, RenameAllUses);
945 renameSuccessorPhis(Root->
getBlock(), IncomingVal, RenameAllUses);
948 while (!WorkStack.
empty()) {
951 IncomingVal = WorkStack.
back().IncomingVal;
953 if (ChildIt == Node->
end()) {
957 ++WorkStack.
back().ChildIt;
961 AlreadyVisited = !Visited.
insert(BB).second;
962 if (SkipVisited && AlreadyVisited) {
969 IncomingVal = &*BlockDefs->rbegin();
971 IncomingVal = renameBlock(BB, IncomingVal, RenameAllUses);
972 renameSuccessorPhis(BB, IncomingVal, RenameAllUses);
981 void MemorySSA::markUnreachableAsLiveOnEntry(
BasicBlock *BB) {
983 "Reachable block found while handling unreachable blocks");
992 auto It = PerBlockAccesses.find(S);
994 if (It == PerBlockAccesses.end() || !isa<MemoryPhi>(It->second->front()))
997 auto *Phi = cast<MemoryPhi>(&Accesses->front());
1001 auto It = PerBlockAccesses.find(BB);
1002 if (It == PerBlockAccesses.end())
1005 auto &Accesses = It->second;
1006 for (
auto AI = Accesses->begin(), AE = Accesses->end(); AI != AE;) {
1007 auto Next = std::next(AI);
1010 if (
auto *UseOrDef = dyn_cast<MemoryUseOrDef>(AI))
1011 UseOrDef->setDefiningAccess(LiveOnEntryDef.get());
1013 Accesses->erase(AI);
1019 : AA(AA), DT(DT),
F(Func), LiveOnEntryDef(nullptr), Walker(nullptr),
1026 for (
const auto &Pair : PerBlockAccesses)
1032 auto Res = PerBlockAccesses.insert(std::make_pair(BB,
nullptr));
1035 Res.first->second = make_unique<AccessList>();
1036 return Res.first->second.get();
1039 auto Res = PerBlockDefs.insert(std::make_pair(BB,
nullptr));
1042 Res.first->second = make_unique<DefsList>();
1043 return Res.first->second.get();
1057 : MSSA(MSSA), Walker(Walker), AA(AA), DT(DT) {
1065 struct MemlocStackInfo {
1068 unsigned long StackEpoch;
1069 unsigned long PopEpoch;
1074 unsigned long LowerBound;
1077 unsigned long LastKill;
1080 void optimizeUsesInBlock(
const BasicBlock *,
unsigned long &,
unsigned long &,
1101 void MemorySSA::OptimizeUses::optimizeUsesInBlock(
1102 const BasicBlock *BB,
unsigned long &StackEpoch,
unsigned long &PopEpoch,
1108 if (Accesses ==
nullptr)
1115 !VersionStack.
empty() &&
1116 "Version stack should have liveOnEntry sentinel dominating everything");
1133 if (isUseTriviallyOptimizableToLiveOnEntry(*AA, MU->getMemoryInst())) {
1138 MemoryLocOrCall UseMLOC(MU);
1139 auto &LocInfo = LocStackInfo[UseMLOC];
1143 if (LocInfo.PopEpoch != PopEpoch) {
1144 LocInfo.PopEpoch = PopEpoch;
1145 LocInfo.StackEpoch = StackEpoch;
1157 if (LocInfo.LowerBoundBlock && LocInfo.LowerBoundBlock != BB &&
1158 !DT->
dominates(LocInfo.LowerBoundBlock, BB)) {
1162 LocInfo.LowerBound = 0;
1163 LocInfo.LowerBoundBlock = VersionStack[0]->getBlock();
1164 LocInfo.LastKillValid =
false;
1166 }
else if (LocInfo.StackEpoch != StackEpoch) {
1170 LocInfo.PopEpoch = PopEpoch;
1171 LocInfo.StackEpoch = StackEpoch;
1173 if (!LocInfo.LastKillValid) {
1174 LocInfo.LastKill = VersionStack.
size() - 1;
1175 LocInfo.LastKillValid =
true;
1180 assert(LocInfo.LowerBound < VersionStack.
size() &&
1181 "Lower bound out of range");
1182 assert(LocInfo.LastKill < VersionStack.
size() &&
1183 "Last kill info out of range");
1185 unsigned long UpperBound = VersionStack.
size() - 1;
1188 DEBUG(
dbgs() <<
"MemorySSA skipping optimization of " << *MU <<
" ("
1189 << *(MU->getMemoryInst()) <<
")"
1190 <<
" because there are " << UpperBound - LocInfo.LowerBound
1191 <<
" stores to disambiguate\n");
1194 LocInfo.LastKillValid =
false;
1197 bool FoundClobberResult =
false;
1198 while (UpperBound > LocInfo.LowerBound) {
1199 if (isa<MemoryPhi>(VersionStack[UpperBound])) {
1204 while (VersionStack[UpperBound] != Result) {
1208 FoundClobberResult =
true;
1212 MemoryDef *MD = cast<MemoryDef>(VersionStack[UpperBound]);
1215 if (!UseMLOC.IsCall && lifetimeEndsAt(MD, UseMLOC.getLoc(), *AA)) {
1218 FoundClobberResult =
true;
1222 FoundClobberResult =
true;
1229 if (FoundClobberResult || UpperBound < LocInfo.LastKill) {
1230 MU->setDefiningAccess(VersionStack[UpperBound],
true);
1232 LocInfo.LastKill = UpperBound;
1236 MU->setDefiningAccess(VersionStack[LocInfo.LastKill],
true);
1238 LocInfo.LowerBound = VersionStack.
size() - 1;
1239 LocInfo.LowerBoundBlock = BB;
1249 unsigned long StackEpoch = 1;
1250 unsigned long PopEpoch = 1;
1253 optimizeUsesInBlock(DomNode->getBlock(), StackEpoch, PopEpoch, VersionStack,
1257 void MemorySSA::placePHINodes(
1262 IDFs.setDefiningBlocks(DefiningBlocks);
1264 IDFs.calculate(IDFBlocks);
1272 for (
auto &BB : IDFBlocks)
1273 createMemoryPhi(BB);
1276 void MemorySSA::buildMemorySSA() {
1284 LiveOnEntryDef = make_unique<MemoryDef>(F.
getContext(),
nullptr,
nullptr,
1285 &StartingPoint, NextID++);
1287 unsigned NextBBNum = 0;
1296 BBNumbers[&
B] = NextBBNum++;
1297 bool InsertIntoDef =
false;
1306 Accesses = getOrCreateAccessList(&B);
1307 Accesses->push_back(MUD);
1308 if (isa<MemoryDef>(MUD)) {
1309 InsertIntoDef =
true;
1311 Defs = getOrCreateDefsList(&B);
1312 Defs->push_back(*MUD);
1316 DefiningBlocks.
insert(&B);
1318 placePHINodes(DefiningBlocks, BBNumbers);
1325 CachingWalker *Walker = getWalkerImpl();
1328 Walker->setAutoResetWalker(
false);
1329 OptimizeUses(
this, Walker, AA, DT).optimizeUses();
1330 Walker->setAutoResetWalker(
true);
1331 Walker->resetClobberWalker();
1336 if (!Visited.
count(&BB))
1337 markUnreachableAsLiveOnEntry(&BB);
1344 return Walker.get();
1346 Walker = make_unique<CachingWalker>(
this, AA, DT);
1347 return Walker.get();
1356 auto *Accesses = getOrCreateAccessList(BB);
1360 if (isa<MemoryPhi>(NewAccess)) {
1361 Accesses->push_front(NewAccess);
1362 auto *Defs = getOrCreateDefsList(BB);
1363 Defs->push_front(*NewAccess);
1366 *Accesses, [](
const MemoryAccess &MA) {
return isa<MemoryPhi>(MA); });
1367 Accesses->insert(AI, NewAccess);
1368 if (!isa<MemoryUse>(NewAccess)) {
1369 auto *Defs = getOrCreateDefsList(BB);
1371 *Defs, [](
const MemoryAccess &MA) {
return isa<MemoryPhi>(MA); });
1372 Defs->insert(DI, *NewAccess);
1376 Accesses->push_back(NewAccess);
1377 if (!isa<MemoryUse>(NewAccess)) {
1378 auto *Defs = getOrCreateDefsList(BB);
1379 Defs->push_back(*NewAccess);
1382 BlockNumberingValid.erase(BB);
1388 bool WasEnd = InsertPt == Accesses->end();
1390 if (!isa<MemoryUse>(What)) {
1391 auto *Defs = getOrCreateDefsList(BB);
1397 Defs->push_back(*What);
1398 }
else if (isa<MemoryDef>(InsertPt)) {
1399 Defs->insert(InsertPt->getDefsIterator(), *What);
1401 while (InsertPt != Accesses->end() && !isa<MemoryDef>(InsertPt))
1404 if (InsertPt == Accesses->end())
1405 Defs->push_back(*What);
1407 Defs->insert(InsertPt->getDefsIterator(), *What);
1410 BlockNumberingValid.erase(BB);
1437 ValueToMemoryAccess[BB] = Phi;
1443 assert(!isa<PHINode>(I) &&
"Cannot create a defined access for a PHI");
1446 NewAccess !=
nullptr &&
1447 "Tried to create a memory access for a non-memory touching instruction");
1456 if (
auto *
SI = dyn_cast<StoreInst>(I)) {
1457 if (!
SI->isUnordered())
1459 }
else if (
auto *LI = dyn_cast<LoadInst>(I)) {
1460 if (!LI->isUnordered())
1472 if (II->getIntrinsicID() == Intrinsic::assume)
1494 "Trying to create a memory access with a non-memory instruction");
1501 ValueToMemoryAccess[
I] = MUD;
1506 bool MemorySSA::dominatesUse(
const MemoryAccess *Replacer,
1508 if (isa<MemoryUseOrDef>(Replacee))
1510 const auto *MP = cast<MemoryPhi>(Replacee);
1514 for (
const Use &Arg : MP->operands()) {
1515 if (Arg.get() != Replacee &&
1525 "Trying to remove memory access that still has uses");
1526 BlockNumbering.erase(MA);
1530 if (!isa<MemoryUse>(MA))
1531 Walker->invalidateInfo(MA);
1540 auto VMA = ValueToMemoryAccess.find(MemoryInst);
1541 if (VMA->second == MA)
1542 ValueToMemoryAccess.erase(VMA);
1554 if (!isa<MemoryUse>(MA)) {
1555 auto DefsIt = PerBlockDefs.find(MA->
getBlock());
1556 std::unique_ptr<DefsList> &Defs = DefsIt->second;
1559 PerBlockDefs.erase(DefsIt);
1564 auto AccessIt = PerBlockAccesses.find(MA->
getBlock());
1565 std::unique_ptr<AccessList> &Accesses = AccessIt->second;
1567 Accesses->erase(MA);
1569 Accesses->remove(MA);
1571 if (Accesses->empty())
1572 PerBlockAccesses.erase(AccessIt);
1577 F.print(OS, &Writer);
1580 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1588 Walker->verify(
this);
1610 assert((!MA || (AL && (isa<MemoryUse>(MA) ||
DL))) &&
1611 "We have memory affecting instructions "
1612 "in this block but they are not in the "
1613 "access list or defs list");
1616 if (isa<MemoryDef>(MA))
1625 assert(AL->size() == ActualAccesses.
size() &&
1626 "We don't have the same number of accesses in the block as on the "
1629 "Either we should have a defs list, or we should have no defs");
1631 "We don't have the same number of defs in the block as on the "
1633 auto ALI = AL->begin();
1634 auto AAI = ActualAccesses.
begin();
1635 while (ALI != AL->end() && AAI != ActualAccesses.
end()) {
1636 assert(&*ALI == *AAI &&
"Not the same accesses in the same order");
1640 ActualAccesses.
clear();
1642 auto DLI =
DL->begin();
1643 auto ADI = ActualDefs.
begin();
1644 while (DLI !=
DL->end() && ADI != ActualDefs.
end()) {
1645 assert(&*DLI == *ADI &&
"Not the same defs in the same order");
1661 for (
const Use &U : MP->uses())
1669 for (
const Use &U : MD->
uses())
1684 "Null def but use not point to live on entry def");
1687 "Did not find use in def's use list");
1700 "Incomplete MemoryPhi Node");
1707 verifyUseInDefs(MA->getDefiningAccess(), MA);
1714 return cast_or_null<MemoryUseOrDef>(ValueToMemoryAccess.lookup(I));
1718 return cast_or_null<MemoryPhi>(ValueToMemoryAccess.lookup(cast<Value>(BB)));
1727 void MemorySSA::renumberBlock(
const BasicBlock *B)
const {
1729 unsigned long CurrentNumber = 0;
1731 assert(AL !=
nullptr &&
"Asking to renumber an empty block");
1732 for (
const auto &I : *AL)
1733 BlockNumbering[&
I] = ++CurrentNumber;
1734 BlockNumberingValid.insert(B);
1746 "Asking for local domination when accesses are in different blocks!");
1748 if (Dominatee == Dominator)
1761 if (!BlockNumberingValid.count(DominatorBlock))
1762 renumberBlock(DominatorBlock);
1764 unsigned long DominatorNum = BlockNumbering.lookup(Dominator);
1766 assert(DominatorNum != 0 &&
"Block was not numbered properly");
1767 unsigned long DominateeNum = BlockNumbering.lookup(Dominatee);
1768 assert(DominateeNum != 0 &&
"Block was not numbered properly");
1769 return DominatorNum < DominateeNum;
1774 if (Dominator == Dominatee)
1786 const Use &Dominatee)
const {
1788 BasicBlock *UseBB = MP->getIncomingBlock(Dominatee);
1790 if (UseBB != Dominator->
getBlock())
1802 switch (getValueID()) {
1803 case MemoryPhiVal:
return static_cast<const MemoryPhi *
>(
this)->
print(OS);
1804 case MemoryDefVal:
return static_cast<const MemoryDef *
>(
this)->
print(OS);
1805 case MemoryUseVal:
return static_cast<const MemoryUse *
>(
this)->
print(OS);
1813 OS <<
getID() <<
" = MemoryDef(";
1814 if (UO && UO->
getID())
1823 OS <<
getID() <<
" = MemoryPhi(";
1824 for (
const auto &
Op : operands()) {
1838 if (
unsigned ID = MA->
getID())
1850 if (UO && UO->
getID())
1859 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1877 auto &MSSA = getAnalysis<MemorySSAWrapperPass>().getMSSA();
1895 OS <<
"MemorySSA for function: " << F.
getName() <<
"\n";
1923 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
1924 auto &AA = getAnalysis<AAResultsWrapperPass>().getAAResults();
1944 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(MA))
1952 MemoryAccess *MemorySSA::CachingWalker::getClobberingMemoryAccess(
1954 MemoryAccess *New = Walker.findClobber(StartingAccess, Q);
1955 #ifdef EXPENSIVE_CHECKS
1956 MemoryAccess *NewNoCache = Walker.findClobber(StartingAccess, Q);
1957 assert(NewNoCache == New &&
"Cache made us hand back a different result?");
1960 if (AutoResetWalker)
1961 resetClobberWalker();
1967 if (isa<MemoryPhi>(StartingAccess))
1968 return StartingAccess;
1970 auto *StartingUseOrDef = cast<MemoryUseOrDef>(StartingAccess);
1972 return StartingUseOrDef;
1974 Instruction *I = StartingUseOrDef->getMemoryInst();
1979 return StartingUseOrDef;
1981 UpwardsMemoryQuery Q;
1982 Q.OriginalAccess = StartingUseOrDef;
1983 Q.StartingLoc = Loc;
1989 MemoryAccess *DefiningAccess = isa<MemoryUse>(StartingUseOrDef)
1990 ? StartingUseOrDef->getDefiningAccess()
1993 MemoryAccess *Clobber = getClobberingMemoryAccess(DefiningAccess, Q);
1994 DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *I <<
" is ");
1995 DEBUG(
dbgs() << *StartingUseOrDef <<
"\n");
1996 DEBUG(
dbgs() <<
"Final Memory SSA clobber for " << *I <<
" is ");
2005 if (!StartingAccess)
2011 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2015 const Instruction *I = StartingAccess->getMemoryInst();
2016 UpwardsMemoryQuery Q(I, StartingAccess);
2021 return StartingAccess;
2023 if (isUseTriviallyOptimizableToLiveOnEntry(*MSSA->AA, I)) {
2025 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2031 MemoryAccess *DefiningAccess = StartingAccess->getDefiningAccess();
2036 return DefiningAccess;
2038 MemoryAccess *Result = getClobberingMemoryAccess(DefiningAccess, Q);
2039 DEBUG(
dbgs() <<
"Starting Memory SSA clobber for " << *I <<
" is ");
2040 DEBUG(
dbgs() << *DefiningAccess <<
"\n");
2041 DEBUG(
dbgs() <<
"Final Memory SSA clobber for " << *I <<
" is ");
2043 if (
auto *MUD = dyn_cast<MemoryUseOrDef>(StartingAccess))
2051 if (
auto *Use = dyn_cast<MemoryUseOrDef>(MA))
2052 return Use->getDefiningAccess();
2058 if (
auto *Use = dyn_cast<MemoryUseOrDef>(StartingAccess))
2059 return Use->getDefiningAccess();
2060 return StartingAccess;
static Reorderability getLoadReorderability(const LoadInst *Use, const LoadInst *MayClobber)
This does one-way checks to see if Use could theoretically be hoisted above MayClobber.
void initializeMemorySSAWrapperPassPass(PassRegistry &)
void push_back(const T &Elt)
typename std::vector< DomTreeNodeBase * >::const_iterator const_iterator
bool dominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in potentially different blocks, determine whether MemoryAccess A dominates...
Safe Stack instrumentation pass
MemoryAccess * getClobberingMemoryAccess(MemoryAccess *) override
Does the same thing as getClobberingMemoryAccess(const Instruction *I), but takes a MemoryAccess inst...
iterator_range< use_iterator > uses()
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
LLVMContext & getContext() const
getContext - Return a reference to the LLVMContext associated with this function. ...
MemoryAccess * getOptimized() const
virtual void verify(const MemorySSA *MSSA)
void dropAllReferences()
Drop all references to operands.
bool isFenceLike() const
Return true if this instruction behaves like a memory fence: it can load or store to memory location ...
virtual void emitBasicBlockStartAnnot(const BasicBlock *BB, formatted_raw_ostream &OS)
emitBasicBlockStartAnnot - This may be implemented to emit a string right after the basic block label...
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
This is the interface for a simple mod/ref and alias analysis over globals.
A Module instance is used to store all the information related to an LLVM module. ...
Result run(Function &F, FunctionAnalysisManager &AM)
This class provides various memory handling functions that manipulate MemoryBlock instances...
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
iplist< MemoryAccess, ilist_tag< MSSAHelpers::AllAccessTag >> AccessList
bool isNoAlias(const MemoryLocation &LocA, const MemoryLocation &LocB)
A trivial helper function to check to see if the specified pointers are no-alias. ...
const DefsList * getBlockDefs(const BasicBlock *BB) const
Return the list of MemoryDef's and MemoryPhi's for a given basic block.
MachineInstrBuilder MachineInstrBuilder &DefMI const MCInstrDesc & Desc
void insertIntoListsForBlock(MemoryAccess *, const BasicBlock *, InsertionPlace)
static bool isOrdered(const Instruction *I)
Extension point for the Value hierarchy.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
unsigned getID() const
Used for debugging and tracking things about MemoryAccesses.
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...
virtual void emitInstructionAnnot(const Instruction *I, formatted_raw_ostream &OS)
emitInstructionAnnot - This may be implemented to emit a string right before an instruction is emitte...
Analysis pass which computes a DominatorTree.
OptimizeUses(MemorySSA *MSSA, MemorySSAWalker *Walker, AliasAnalysis *AA, DominatorTree *DT)
An instruction for reading from memory.
The access modifies the value stored in memory.
INITIALIZE_PASS_BEGIN(MemorySSAWrapperPass,"memoryssa","Memory SSA", false, true) INITIALIZE_PASS_END(MemorySSAWrapperPass
void setIncomingValue(unsigned I, MemoryAccess *V)
StringRef getName() const
Return a constant reference to the value's name.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
Represents read-only accesses to memory.
This class is a batch walker of all MemoryUse's in the program, and points their defining access at t...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
ModRefInfo
Flags indicating whether a memory access modifies or references memory.
static Value * getPointerOperand(Instruction &Inst)
~CachingWalker() override
A MemorySSAWalker that does AA walks to disambiguate accesses.
A Use represents the edge between a Value definition and its users.
AccessList * getWritableBlockAccesses(const BasicBlock *BB) const
MemorySSAAnnotatedWriter(const MemorySSA *M)
auto find_if_not(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
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.
MemoryUseOrDef * getMemoryAccess(const Instruction *) const
Given a memory Mod/Ref'ing instruction, get the MemorySSA access associated with it.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
The access references the value stored in memory.
APInt operator*(APInt a, uint64_t RHS)
LLVM_NODISCARD bool empty() const
A simple intrusive list implementation.
BasicBlock * getBlock() const
User * getUser() const LLVM_READONLY
Returns the User that contains this Use.
CachingWalker(MemorySSA *, AliasAnalysis *, DominatorTree *)
ppc ctr loops PowerPC CTR Loops Verify
static int getID(struct InternalInstruction *insn, const void *miiArg)
upward_defs_iterator upward_defs_end()
DomTreeNodeBase * getIDom() const
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.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
Base class for the actual dominator tree node.
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
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...
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
static bool instructionClobbersQuery(MemoryDef *MD, const MemoryLocation &UseLoc, const Instruction *UseInst, AliasAnalysis &AA)
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 setAutoResetWalker(bool AutoReset)
Whether we call resetClobberWalker() after each time we actually walk to answer a clobber query...
The access neither references nor modifies the value stored in memory.
bool verify(const TargetRegisterInfo &TRI) const
Check that information hold by this instance make sense for the given TRI.
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)
void verifyAnalysis() const override
verifyAnalysis() - This member can be implemented by a analysis pass to check state of analysis infor...
void renamePass(BasicBlock *BB, MemoryAccess *IncomingVal, SmallPtrSetImpl< BasicBlock * > &Visited)
A set of analyses that are preserved following a run of a transformation pass.
LLVM Basic Block Representation.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void optimizeUses()
Optimize uses to point to their actual clobbering definitions.
void verifyOrdering(Function &F) const
Verify that the order and existence of MemoryAccesses matches the order and existence of memory affec...
static bool isAtLeastOrStrongerThan(AtomicOrdering ao, AtomicOrdering other)
void print(raw_ostream &OS) const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
void addIncoming(MemoryAccess *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
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
MemorySSA(Function &, AliasAnalysis *, DominatorTree *)
void print(raw_ostream &OS) const
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...
bool runOnFunction(Function &) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
MemorySSAWalker(MemorySSA *)
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.
bool locallyDominates(const MemoryAccess *A, const MemoryAccess *B) const
Given two memory accesses in the same basic block, determine whether MemoryAccess A dominates MemoryA...
#define LLVM_ATTRIBUTE_UNUSED
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
FunctionPass class - This class is used to implement most global optimizations.
Interval::pred_iterator pred_end(Interval *I)
Memory true print Memory SSA Printer
void verifyDefUses(Function &F) const
Verify the immediate use information, by walking all the memory accesses and verifying that...
static bool instructionClobbersQuery(MemoryDef *MD, const MemoryUseOrDef *MU, const MemoryLocOrCall &UseMLOC, AliasAnalysis &AA)
MemoryAccess * getIncomingValue(unsigned I) const
Return incoming value number x.
void print(raw_ostream &OS, const Module *M=nullptr) const override
print - Print out the internal state of the pass.
static const char LiveOnEntryStr[]
void verifyDomination(Function &F) const
Verify the domination properties of MemorySSA by checking that each definition dominates all of its u...
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
LLVMContext & getContext() const
All values hold a context through their type.
An intrusive list with ownership and callbacks specified/controlled by ilist_traits, only with API safe for polymorphic types.
MemoryAccess * getLiveOnEntryDef() const
MemorySSAWalker * getWalker()
void removeFromLists(MemoryAccess *, bool ShouldDelete=true)
Properly remove MA from all of MemorySSA's lists.
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Representation for a specific memory location.
void insertIntoListsBefore(MemoryAccess *, const BasicBlock *, AccessList::iterator)
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
static bool defClobbersUseOrDef(MemoryDef *MD, const MemoryUseOrDef *MU, AliasAnalysis &AA)
void print(raw_ostream &OS) const
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
simple_ilist< MemoryAccess, ilist_tag< MSSAHelpers::DefsOnlyTag >> DefsList
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void print(raw_ostream &OS) const
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
void verify(const MemorySSA *MSSA) override
const BasicBlock & getEntryBlock() const
void moveTo(MemoryUseOrDef *What, BasicBlock *BB, AccessList::iterator Where)
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.
Target - Wrapper for Target specific information.
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
void verifyMemorySSA() const
Verify that MemorySSA is self consistent (IE definitions dominate all uses, uses appear in the right ...
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.
MemoryUseOrDef * createDefinedAccess(Instruction *, MemoryAccess *)
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.
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)"))
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void resetClobberWalker()
Drop the walker's persistent data structures.
llvm_unreachable("Unknown RegBank!")
void initializeMemorySSAPrinterLegacyPassPass(PassRegistry &)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
iterator_range< def_chain_iterator< T > > def_chain(T MA, MemoryAccess *UpTo=nullptr)
void emplace_back(ArgTypes &&...Args)
This file provides utility analysis objects describing memory locations.
Establish a view to a call site for examination.
void setDefiningAccess(MemoryAccess *DMA, bool Optimized=false)
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
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)
AnalysisUsage & addRequiredTransitive()
MemorySSAPrinterLegacyPass()
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.
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
void removeFromLookups(MemoryAccess *)
Properly remove MA from all of MemorySSA's lookup tables.
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."))
LLVMContext & getContext() const
Get the context in which this basic block lives.
void setOptimized(MemoryAccess *MA)
LLVM Value Representation.
static MemoryLocOrCall getTombstoneKey()
succ_range successors(BasicBlock *BB)
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
upward_defs_iterator upward_defs_begin(const MemoryAccessPair &Pair)
DomTreeNodeBase< NodeT > * getRootNode()
getRootNode - This returns the entry node for the CFG of the function.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This class implements an extremely fast bulk output stream that can only output to a stream...
static unsigned getHashValue(const MemoryLocOrCall &MLOC)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
void invalidateInfo(MemoryAccess *) override
Given a memory access, invalidate anything this walker knows about that access.
void print(raw_ostream &) const
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.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
DefsList * getWritableBlockDefs(const BasicBlock *BB) const
bool operator==(uint64_t V1, const APInt &V2)
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
const AccessList * getBlockAccesses(const BasicBlock *BB) const
Return the list of MemoryAccess's for a given basic block.
void releaseMemory() override
releaseMemory() - This member can be implemented by a pass if it wants to be able to release its memo...
static MemoryLocOrCall getEmptyKey()
A special type used by analysis passes to provide an address that identifies that particular analysis...
const BasicBlock * getParent() const
reverse_iterator rbegin()
std::pair< MemoryAccess *, MemoryLocation > MemoryAccessPair
bool isLiveOnEntryDef(const MemoryAccess *MA) const
Return true if MA represents the live on entry value.
A wrapper class for inspecting calls to intrinsic functions.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.