124 using namespace llvm;
129 #define DEBUG_TYPE "newgvn" 131 STATISTIC(NumGVNInstrDeleted,
"Number of instructions deleted");
132 STATISTIC(NumGVNBlocksDeleted,
"Number of blocks deleted");
133 STATISTIC(NumGVNOpsSimplified,
"Number of Expressions simplified");
134 STATISTIC(NumGVNPhisAllSame,
"Number of PHIs whos arguments are all the same");
136 "Maximum Number of iterations it took to converge GVN");
137 STATISTIC(NumGVNLeaderChanges,
"Number of leader changes");
138 STATISTIC(NumGVNSortedLeaderChanges,
"Number of sorted leader changes");
139 STATISTIC(NumGVNAvoidedSortedLeaderChanges,
140 "Number of avoided sorted leader changes");
141 STATISTIC(NumGVNDeadStores,
"Number of redundant/dead stores eliminated");
142 STATISTIC(NumGVNPHIOfOpsCreated,
"Number of PHI of ops created");
144 "Number of things eliminated using PHI of ops");
146 "Controls which instructions are value numbered");
148 "Controls which instructions we create phi of ops for");
165 namespace GVNExpression {
189 TarjanSCC() : Components(1) {}
192 if (Root.lookup(Start) == 0)
197 unsigned ComponentID = ValueToComponent.lookup(V);
200 "Asking for a component for a value we never processed");
201 return Components[ComponentID];
208 unsigned int OurDFS = DFSNum;
210 if (
auto *InstOp = dyn_cast<Instruction>(
Op)) {
211 if (Root.lookup(
Op) == 0)
213 if (!InComponent.count(
Op))
214 Root[I] = std::min(Root.lookup(I), Root.lookup(
Op));
221 if (Root.lookup(I) == OurDFS) {
222 unsigned ComponentID = Components.size();
223 Components.resize(Components.size() + 1);
224 auto &Component = Components.back();
227 InComponent.insert(I);
228 ValueToComponent[
I] = ComponentID;
230 while (!Stack.empty() && Root.lookup(Stack.back()) >= OurDFS) {
231 auto *Member = Stack.back();
233 Component.insert(Member);
234 InComponent.insert(Member);
235 ValueToComponent[Member] = ComponentID;
244 unsigned int DFSNum = 1;
294 class CongruenceClass {
296 using MemberType =
Value;
301 explicit CongruenceClass(
unsigned ID) : ID(ID) {}
303 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
305 unsigned getID()
const {
return ID; }
309 bool isDead()
const {
312 return empty() && memory_empty();
316 Value *getLeader()
const {
return RepLeader; }
317 void setLeader(
Value *Leader) { RepLeader = Leader; }
318 const std::pair<Value *, unsigned int> &getNextLeader()
const {
321 void resetNextLeader() { NextLeader = {
nullptr, ~0}; }
322 void addPossibleNextLeader(std::pair<Value *, unsigned int> LeaderPair) {
323 if (LeaderPair.second < NextLeader.second)
324 NextLeader = LeaderPair;
327 Value *getStoredValue()
const {
return RepStoredValue; }
328 void setStoredValue(
Value *Leader) { RepStoredValue = Leader; }
329 const MemoryAccess *getMemoryLeader()
const {
return RepMemoryAccess; }
330 void setMemoryLeader(
const MemoryAccess *Leader) { RepMemoryAccess = Leader; }
333 const Expression *getDefiningExpr()
const {
return DefiningExpr; }
336 bool empty()
const {
return Members.empty(); }
337 unsigned size()
const {
return Members.size(); }
338 MemberSet::const_iterator
begin()
const {
return Members.
begin(); }
339 MemberSet::const_iterator
end()
const {
return Members.
end(); }
340 void insert(MemberType *M) { Members.insert(M); }
341 void erase(MemberType *M) { Members.erase(M); }
342 void swap(MemberSet &Other) { Members.swap(Other); }
345 bool memory_empty()
const {
return MemoryMembers.empty(); }
346 unsigned memory_size()
const {
return MemoryMembers.size(); }
347 MemoryMemberSet::const_iterator memory_begin()
const {
348 return MemoryMembers.begin();
350 MemoryMemberSet::const_iterator memory_end()
const {
351 return MemoryMembers.end();
354 return make_range(memory_begin(), memory_end());
357 void memory_insert(
const MemoryMemberType *M) { MemoryMembers.insert(M); }
358 void memory_erase(
const MemoryMemberType *M) { MemoryMembers.erase(M); }
361 unsigned getStoreCount()
const {
return StoreCount; }
362 void incStoreCount() { ++StoreCount; }
363 void decStoreCount() {
364 assert(StoreCount != 0 &&
"Store count went negative");
369 bool definesNoMemory()
const {
return StoreCount == 0 && memory_empty(); }
373 bool isEquivalentTo(
const CongruenceClass *Other)
const {
379 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
380 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
381 Other->RepMemoryAccess))
383 if (DefiningExpr != Other->DefiningExpr)
384 if (!DefiningExpr || !Other->DefiningExpr ||
385 *DefiningExpr != *Other->DefiningExpr)
388 if (Members.size() != Other->Members.size())
392 [&](
const Value *V) {
return Other->Members.count(V); });
399 Value *RepLeader =
nullptr;
403 std::pair<Value *, unsigned int> NextLeader = {
nullptr, ~0U};
406 Value *RepStoredValue =
nullptr;
421 MemoryMemberSet MemoryMembers;
446 auto Val =
static_cast<uintptr_t
>(-1);
447 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
448 return reinterpret_cast<const Expression *
>(Val);
452 auto Val =
static_cast<uintptr_t
>(~1U);
453 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
454 return reinterpret_cast<const Expression *
>(Val);
466 if (RHS == getTombstoneKey() || RHS == getEmptyKey())
474 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
475 LHS == getEmptyKey() || RHS == getEmptyKey())
499 std::unique_ptr<PredicateInfo> PredInfo;
505 mutable TarjanSCC SCCFinder;
509 unsigned int NumFuncArgs = 0;
520 CongruenceClass *TOPClass =
nullptr;
521 std::vector<CongruenceClass *> CongruenceClasses;
522 unsigned NextCongruenceNum = 0;
553 ExpressionToPhiOfOps;
602 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
605 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
610 ExpressionClassMap ExpressionToClass;
661 :
F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
662 PredInfo(std::make_unique<PredicateInfo>(F, *DT, *AC)),
663 SQ(DL, TLI, DT, AC,
nullptr,
false) {}
675 using ValPair = std::pair<Value *, BasicBlock *>;
679 bool &OriginalOpsConstant)
const;
692 createAggregateValueExpression(
Instruction *)
const;
696 CongruenceClass *createCongruenceClass(
Value *Leader,
const Expression *
E) {
697 auto *result =
new CongruenceClass(NextCongruenceNum++, Leader, E);
698 CongruenceClasses.emplace_back(result);
703 auto *CC = createCongruenceClass(
nullptr,
nullptr);
704 CC->setMemoryLeader(MA);
708 CongruenceClass *ensureLeaderOfMemoryClass(
MemoryAccess *MA) {
709 auto *CC = getMemoryClass(MA);
710 if (CC->getMemoryLeader() != MA)
711 CC = createMemoryClass(MA);
715 CongruenceClass *createSingletonCongruenceClass(
Value *Member) {
716 CongruenceClass *CClass = createCongruenceClass(Member,
nullptr);
717 CClass->insert(Member);
718 ValueToClass[Member] = CClass;
722 void initializeCongruenceClasses(
Function &F);
763 CongruenceClass *getClassForExpression(
const Expression *E)
const;
766 CongruenceClass *, CongruenceClass *);
768 CongruenceClass *, CongruenceClass *);
769 Value *getNextValueLeader(CongruenceClass *)
const;
770 const MemoryAccess *getNextMemoryLeader(CongruenceClass *)
const;
772 CongruenceClass *getMemoryClass(
const MemoryAccess *MA)
const;
777 unsigned int getRank(
const Value *)
const;
778 bool shouldSwapOperands(
const Value *,
const Value *)
const;
783 Value *findConditionEquivalence(
Value *)
const;
787 void convertClassToDFSOrdered(
const CongruenceClass &,
791 void convertClassToLoadsAndStores(
const CongruenceClass &,
794 bool eliminateInstructions(
Function &);
805 template <
typename Map,
typename KeyType,
typename Func>
806 void for_each_found(Map &,
const KeyType &, Func);
807 template <
typename Map,
typename KeyType>
808 void touchAndErase(Map &,
const KeyType &);
809 void markUsersTouched(
Value *);
813 void markValueLeaderChangeTouched(CongruenceClass *CC);
814 void markMemoryLeaderChangeTouched(CongruenceClass *CC);
815 void markPhiOfOpsChanged(
const Expression *E);
821 void iterateTouchedInstructions();
824 void cleanupTables();
825 std::pair<unsigned, unsigned> assignDFSNumbers(
BasicBlock *,
unsigned);
826 void updateProcessedCount(
const Value *V);
827 void verifyMemoryCongruency()
const;
828 void verifyIterationSettled(
Function &F);
829 void verifyStoreExpressions()
const;
833 void deleteExpression(
const Expression *E)
const;
837 template <
class T,
class Range>
T *getMinDFSOfRange(
const Range &)
const;
839 unsigned InstrToDFSNum(
const Value *V)
const {
840 assert(isa<Instruction>(V) &&
"This should not be used for MemoryAccesses");
841 return InstrDFS.
lookup(V);
845 return MemoryToDFSNum(MA);
848 Value *InstrFromDFSNum(
unsigned DFSNum) {
return DFSToInstr[DFSNum]; }
853 unsigned MemoryToDFSNum(
const Value *MA)
const {
854 assert(isa<MemoryAccess>(MA) &&
855 "This should not be used with instructions");
856 return isa<MemoryUseOrDef>(MA)
857 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
866 int64_t StartingVNCounter = 0;
871 template <
typename T>
873 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
875 return LHS.MemoryExpression::equals(RHS);
886 if (
const auto *S = dyn_cast<StoreExpression>(&Other))
887 if (getStoredValue() != S->getStoredValue())
895 RPOOrdering.lookup(DT->getNode(From)) >=
896 RPOOrdering.lookup(DT->getNode(To));
907 auto *Result = MSSA->getMemoryAccess(I);
908 return Result ? Result : TempToMemory.lookup(I);
913 return MSSA->getMemoryAccess(BB);
918 if (
auto *I = dyn_cast<Instruction>(V)) {
922 Parent = TempToBlock.lookup(V);
923 assert(Parent &&
"Every fake instruction should have a block");
928 assert(MP &&
"Should have been an instruction or a MemoryPhi");
929 return MP->getBlock();
935 void NewGVN::deleteExpression(
const Expression *
E)
const {
936 assert(isa<BasicExpression>(E));
937 auto *BE = cast<BasicExpression>(
E);
939 ExpressionAllocator.Deallocate(E);
944 if (
auto *II = dyn_cast<IntrinsicInst>(V))
945 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
946 return II->getOperand(0);
957 return CO && isa<PHINode>(CO);
964 llvm::sort(Ops, [&](
const ValPair &P1,
const ValPair &P2) {
965 return BlockInstRange.lookup(P1.second).first <
966 BlockInstRange.lookup(P2.second).first;
974 return isa<Constant>(V) || isa<Argument>(V);
986 bool &OriginalOpsConstant)
const {
987 unsigned NumOps = PHIOperands.
size();
988 auto *E =
new (ExpressionAllocator)
PHIExpression(NumOps, PHIBlock);
990 E->allocateOperands(ArgRecycler, ExpressionAllocator);
991 E->setType(PHIOperands.
begin()->first->getType());
997 if (
auto *PHIOp = dyn_cast<PHINode>(I))
1000 if (!ReachableEdges.count({BB, PHIBlock}))
1003 if (ValueToClass.lookup(P.first) == TOPClass)
1005 OriginalOpsConstant = OriginalOpsConstant && isa<Constant>(P.first);
1006 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
1007 return lookupOperandLeader(P.first) !=
I;
1010 [&](
const ValPair &
P) ->
Value * {
1011 return lookupOperandLeader(P.first);
1019 bool AllConstant =
true;
1020 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I))
1030 auto Operand = lookupOperandLeader(
O);
1031 AllConstant = AllConstant && isa<Constant>(Operand);
1038 const Expression *NewGVN::createBinaryExpression(
unsigned Opcode,
Type *
T,
1051 if (shouldSwapOperands(Arg1, Arg2))
1058 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1071 if (
auto *
C = dyn_cast<Constant>(V)) {
1074 <<
" constant " << *
C <<
"\n");
1075 NumGVNOpsSimplified++;
1076 assert(isa<BasicExpression>(E) &&
1077 "We should always have had a basic expression here");
1078 deleteExpression(E);
1079 return createConstantExpression(
C);
1080 }
else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1083 <<
" variable " << *V <<
"\n");
1084 deleteExpression(E);
1085 return createVariableExpression(V);
1088 CongruenceClass *CC = ValueToClass.lookup(V);
1090 if (CC->getLeader() && CC->getLeader() !=
I) {
1095 if (!AllTempInstructions.count(I))
1096 addAdditionalUsers(V, I);
1098 return createVariableOrConstant(CC->getLeader());
1100 if (CC->getDefiningExpr()) {
1105 if (!AllTempInstructions.count(I))
1106 addAdditionalUsers(V, I);
1111 <<
" expression " << *CC->getDefiningExpr() <<
"\n");
1112 NumGVNOpsSimplified++;
1113 deleteExpression(E);
1114 return CC->getDefiningExpr();
1127 bool AllConstant = setBasicExpressionInfo(I, E);
1135 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
1136 E->swapOperands(0, 1);
1139 if (
auto *CI = dyn_cast<CmpInst>(I)) {
1143 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
1144 E->swapOperands(0, 1);
1147 E->
setOpcode((CI->getOpcode() << 8) | Predicate);
1150 "Wrong types on cmp instruction");
1155 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1157 }
else if (isa<SelectInst>(I)) {
1158 if (isa<Constant>(E->getOperand(0)) ||
1159 E->getOperand(1) == E->getOperand(2)) {
1163 E->getOperand(2), SQ);
1164 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1170 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1172 }
else if (
auto *CI = dyn_cast<CastInst>(I)) {
1175 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1177 }
else if (isa<GetElementPtrInst>(I)) {
1180 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1182 }
else if (AllConstant) {
1195 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1202 NewGVN::createAggregateValueExpression(
Instruction *I)
const {
1203 if (
auto *II = dyn_cast<InsertValueInst>(I)) {
1204 auto *E =
new (ExpressionAllocator)
1206 setBasicExpressionInfo(I, E);
1207 E->allocateIntOperands(ExpressionAllocator);
1210 }
else if (
auto *EI = dyn_cast<ExtractValueInst>(I)) {
1211 auto *E =
new (ExpressionAllocator)
1213 setBasicExpressionInfo(EI, E);
1214 E->allocateIntOperands(ExpressionAllocator);
1224 return SingletonDeadExpression;
1234 if (
auto *
C = dyn_cast<Constant>(V))
1235 return createConstantExpression(
C);
1236 return createVariableExpression(V);
1256 setBasicExpressionInfo(CI, E);
1261 bool NewGVN::someEquivalentDominates(
const Instruction *Inst,
1263 auto *CC = ValueToClass.lookup(Inst);
1284 if (DT->dominates(cast<Instruction>(CC->getLeader()), U))
1286 if (CC->getNextLeader().first &&
1287 DT->dominates(cast<Instruction>(CC->getNextLeader().first), U))
1290 return Member != CC->getLeader() &&
1291 DT->dominates(cast<Instruction>(Member), U);
1297 Value *NewGVN::lookupOperandLeader(
Value *V)
const {
1298 CongruenceClass *CC = ValueToClass.lookup(V);
1305 return CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
1312 auto *CC = getMemoryClass(MA);
1313 assert(CC->getMemoryLeader() &&
1314 "Every MemoryAccess should be mapped to a congruence class with a " 1315 "representative memory access");
1316 return CC->getMemoryLeader();
1322 bool NewGVN::isMemoryAccessTOP(
const MemoryAccess *MA)
const {
1323 return getMemoryClass(MA) == TOPClass;
1330 new (ExpressionAllocator)
LoadExpression(1, LI, lookupMemoryLeader(MA));
1331 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1332 E->setType(LoadType);
1336 E->op_push_back(PointerOp);
1349 auto *E =
new (ExpressionAllocator)
1367 auto *SI = cast<StoreInst>(
I);
1368 auto *StoreAccess = getMemoryAccess(SI);
1370 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1372 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1374 StoreRHS = lookupMemoryLeader(StoreRHS);
1375 if (StoreRHS != StoreAccess->getDefiningAccess())
1376 addMemoryUsers(StoreRHS, StoreAccess);
1378 if (StoreRHS == StoreAccess)
1379 StoreRHS = MSSA->getLiveOnEntryDef();
1385 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1386 const auto *LastCC = ExpressionToClass.lookup(LastStore);
1392 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
1398 if (
auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
1400 LastStore->getOperand(0)) &&
1401 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
1404 deleteExpression(LastStore);
1410 return createStoreExpression(SI, StoreAccess);
1416 NewGVN::performSymbolicLoadCoercion(
Type *LoadType,
Value *LoadPtr,
1420 if (
auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1424 if (LI->
isAtomic() > DepSI->isAtomic() ||
1425 LoadType == DepSI->getValueOperand()->getType())
1429 if (
auto *C = dyn_cast<Constant>(
1430 lookupOperandLeader(DepSI->getValueOperand()))) {
1432 <<
" to constant " << *C <<
"\n");
1433 return createConstantExpression(
1437 }
else if (
auto *DepLI = dyn_cast<LoadInst>(DepInst)) {
1439 if (LI->
isAtomic() > DepLI->isAtomic())
1444 if (
auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1445 if (
auto *PossibleConstant =
1448 <<
" to constant " << *PossibleConstant <<
"\n");
1449 return createConstantExpression(PossibleConstant);
1452 }
else if (
auto *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1455 if (
auto *PossibleConstant =
1458 <<
" to constant " << *PossibleConstant <<
"\n");
1459 return createConstantExpression(PossibleConstant);
1466 if (LoadPtr != lookupOperandLeader(DepInst) &&
1467 !AA->isMustAlias(LoadPtr, DepInst))
1478 else if (
auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1479 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1492 auto *LI = cast<LoadInst>(
I);
1501 if (isa<UndefValue>(LoadAddressLeader))
1505 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
1507 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1508 if (
auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1511 if (!ReachableBlocks.count(DefiningInst->
getParent()))
1517 if (
const auto *CoercionResult =
1518 performSymbolicLoadCoercion(LI->
getType(), LoadAddressLeader, LI,
1519 DefiningInst, DefiningAccess))
1520 return CoercionResult;
1524 const auto *
LE = createLoadExpression(LI->
getType(), LoadAddressLeader, LI,
1528 if (
LE->getMemoryLeader() != DefiningAccess)
1529 addMemoryUsers(
LE->getMemoryLeader(), OriginalAccess);
1534 NewGVN::performSymbolicPredicateInfoEvaluation(
Instruction *I)
const {
1535 auto *PI = PredInfo->getPredicateInfoFor(I);
1539 LLVM_DEBUG(
dbgs() <<
"Found predicate info from instruction !\n");
1546 auto *Cond = PWC->Condition;
1550 if (CopyOf == Cond) {
1553 if (isa<PredicateAssume>(PI))
1555 if (
auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1556 if (PBranch->TrueEdge)
1560 if (
auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1561 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
1578 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
1579 LLVM_DEBUG(
dbgs() <<
"Copy is not of any condition operands!\n");
1582 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1583 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
1584 bool SwappedOps =
false;
1586 if (shouldSwapOperands(FirstOp, SecondOp)) {
1591 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1593 if (isa<PredicateAssume>(PI)) {
1596 addPredicateUsers(PI, I);
1597 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1599 return createVariableOrConstant(FirstOp);
1602 if (
const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1610 addPredicateUsers(PI, I);
1611 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1613 return createVariableOrConstant(FirstOp);
1618 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1619 addPredicateUsers(PI, I);
1620 addAdditionalUsers(SwappedOps ? Cmp->getOperand(1) : Cmp->getOperand(0),
1622 return createConstantExpression(cast<Constant>(FirstOp));
1630 auto *CI = cast<CallInst>(
I);
1631 if (
auto *II = dyn_cast<IntrinsicInst>(I)) {
1633 if (
auto *ReturnedValue = II->getReturnedArgOperand()) {
1634 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1635 if (
const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1637 return createVariableOrConstant(ReturnedValue);
1640 if (AA->doesNotAccessMemory(CI)) {
1641 return createCallExpression(CI, TOPClass->getMemoryLeader());
1642 }
else if (AA->onlyReadsMemory(CI)) {
1643 if (
auto *MA = MSSA->getMemoryAccess(CI)) {
1644 auto *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(MA);
1645 return createCallExpression(CI, DefiningAccess);
1647 return createCallExpression(CI, TOPClass->getMemoryLeader());
1653 CongruenceClass *NewGVN::getMemoryClass(
const MemoryAccess *MA)
const {
1654 auto *Result = MemoryAccessToClass.lookup(MA);
1655 assert(Result &&
"Should have found memory class");
1662 CongruenceClass *NewClass) {
1664 "Every MemoryAccess should be getting mapped to a non-null class");
1668 <<
" with current MemoryAccess leader ");
1671 auto LookupResult = MemoryAccessToClass.find(From);
1672 bool Changed =
false;
1674 if (LookupResult != MemoryAccessToClass.end()) {
1675 auto *OldClass = LookupResult->second;
1676 if (OldClass != NewClass) {
1678 if (
auto *MP = dyn_cast<MemoryPhi>(From)) {
1679 OldClass->memory_erase(MP);
1680 NewClass->memory_insert(MP);
1682 if (OldClass->getMemoryLeader() ==
From) {
1683 if (OldClass->definesNoMemory()) {
1684 OldClass->setMemoryLeader(
nullptr);
1686 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1688 << OldClass->getID() <<
" to " 1689 << *OldClass->getMemoryLeader()
1690 <<
" due to removal of a memory member " << *From
1692 markMemoryLeaderChangeTouched(OldClass);
1697 LookupResult->second = NewClass;
1709 bool NewGVN::isCycleFree(
const Instruction *I)
const {
1715 auto ICS = InstCycleState.lookup(I);
1716 if (ICS == ICS_Unknown) {
1718 auto &SCC = SCCFinder.getComponentFor(I);
1720 if (SCC.size() == 1)
1721 InstCycleState.insert({I, ICS_CycleFree});
1726 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
1727 for (
auto *Member : SCC)
1728 if (
auto *MemberPhi = dyn_cast<PHINode>(Member))
1729 InstCycleState.insert({MemberPhi, ICS});
1732 if (ICS == ICS_Cycle)
1743 bool HasBackedge =
false;
1748 bool OriginalOpsConstant =
true;
1749 auto *E = cast<PHIExpression>(createPHIExpression(
1750 PHIOps, I, PHIBlock, HasBackedge, OriginalOpsConstant));
1754 bool HasUndef =
false;
1756 if (isa<UndefValue>(
Arg)) {
1763 if (Filtered.empty()) {
1768 dbgs() <<
"PHI Node " << *I
1769 <<
" has no non-undef arguments, valuing it as undef\n");
1773 LLVM_DEBUG(
dbgs() <<
"No arguments of PHI node " << *I <<
" are live\n");
1774 deleteExpression(E);
1775 return createDeadExpression();
1777 Value *AllSameValue = *(Filtered.begin());
1796 if (HasBackedge && !OriginalOpsConstant &&
1797 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
1801 if (
auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1802 if (!someEquivalentDominates(AllSameInst, I))
1808 if (isa<Instruction>(AllSameValue) &&
1809 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1811 NumGVNPhisAllSame++;
1812 LLVM_DEBUG(
dbgs() <<
"Simplified PHI node " << *I <<
" to " << *AllSameValue
1814 deleteExpression(E);
1815 return createVariableOrConstant(AllSameValue);
1821 NewGVN::performSymbolicAggrValueEvaluation(
Instruction *I)
const {
1822 if (
auto *EI = dyn_cast<ExtractValueInst>(I)) {
1824 if (WO && EI->getNumIndices() == 1 && *EI->idx_begin() == 0)
1828 return createBinaryExpression(WO->getBinaryOp(), EI->getType(),
1829 WO->getLHS(), WO->getRHS(),
I);
1832 return createAggregateValueExpression(I);
1836 assert(isa<CmpInst>(I) &&
"Expected a cmp instruction.");
1838 auto *CI = cast<CmpInst>(
I);
1841 auto Op0 = lookupOperandLeader(CI->
getOperand(0));
1842 auto Op1 = lookupOperandLeader(CI->
getOperand(1));
1843 auto OurPredicate = CI->getPredicate();
1844 if (shouldSwapOperands(Op0, Op1)) {
1846 OurPredicate = CI->getSwappedPredicate();
1853 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1854 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1859 if (CI->isTrueWhenEqual())
1861 else if (CI->isFalseWhenEqual())
1891 auto *PI = PredInfo->getPredicateInfoFor(
Op);
1892 if (
const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1893 if (PI == LastPredInfo)
1898 if (!DT->dominates(PBranch->To, getBlockForValue(I)))
1908 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1909 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1911 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1913 BranchPredicate = BranchCond->getSwappedPredicate();
1915 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1916 if (PBranch->TrueEdge) {
1921 addPredicateUsers(PI, I);
1922 return createConstantExpression(
1928 addPredicateUsers(PI, I);
1929 return createConstantExpression(
1935 if (BranchPredicate == OurPredicate) {
1936 addPredicateUsers(PI, I);
1938 return createConstantExpression(
1940 }
else if (BranchPredicate ==
1942 addPredicateUsers(PI, I);
1944 return createConstantExpression(
1952 return createExpression(I);
1957 NewGVN::performSymbolicEvaluation(
Value *V,
1960 if (
auto *C = dyn_cast<Constant>(V))
1961 E = createConstantExpression(C);
1962 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1963 E = createVariableExpression(V);
1968 auto *I = cast<Instruction>(V);
1970 case Instruction::ExtractValue:
1971 case Instruction::InsertValue:
1972 E = performSymbolicAggrValueEvaluation(I);
1974 case Instruction::PHI: {
1976 auto *PN = cast<PHINode>(
I);
1977 for (
unsigned i = 0; i < PN->getNumOperands(); ++i)
1978 Ops.
push_back({PN->getIncomingValue(i), PN->getIncomingBlock(i)});
1981 E = performSymbolicPHIEvaluation(Ops, I, getBlockForValue(I));
1984 E = performSymbolicCallEvaluation(I);
1987 E = performSymbolicStoreEvaluation(I);
1990 E = performSymbolicLoadEvaluation(I);
1992 case Instruction::BitCast:
1993 case Instruction::AddrSpaceCast:
1994 E = createExpression(I);
1996 case Instruction::ICmp:
1997 case Instruction::FCmp:
1998 E = performSymbolicCmpEvaluation(I);
2000 case Instruction::FNeg:
2002 case Instruction::FAdd:
2003 case Instruction::Sub:
2004 case Instruction::FSub:
2005 case Instruction::Mul:
2006 case Instruction::FMul:
2007 case Instruction::UDiv:
2008 case Instruction::SDiv:
2009 case Instruction::FDiv:
2010 case Instruction::URem:
2011 case Instruction::SRem:
2012 case Instruction::FRem:
2013 case Instruction::Shl:
2014 case Instruction::LShr:
2015 case Instruction::AShr:
2016 case Instruction::And:
2017 case Instruction::Or:
2018 case Instruction::Xor:
2019 case Instruction::Trunc:
2020 case Instruction::ZExt:
2021 case Instruction::SExt:
2022 case Instruction::FPToUI:
2023 case Instruction::FPToSI:
2024 case Instruction::UIToFP:
2025 case Instruction::SIToFP:
2026 case Instruction::FPTrunc:
2027 case Instruction::FPExt:
2028 case Instruction::PtrToInt:
2029 case Instruction::IntToPtr:
2031 case Instruction::ExtractElement:
2032 case Instruction::InsertElement:
2033 case Instruction::ShuffleVector:
2034 case Instruction::GetElementPtr:
2035 E = createExpression(I);
2046 template <
typename Map,
typename KeyType,
typename Func>
2047 void NewGVN::for_each_found(Map &M,
const KeyType &
Key, Func
F) {
2048 const auto Result = M.find_as(Key);
2049 if (Result != M.end())
2050 for (
typename Map::mapped_type::value_type Mapped : Result->second)
2056 template <
typename Map,
typename KeyType>
2057 void NewGVN::touchAndErase(Map &M,
const KeyType &Key) {
2058 const auto Result = M.find_as(Key);
2059 if (Result != M.end()) {
2060 for (
const typename Map::mapped_type::value_type Mapped : Result->second)
2061 TouchedInstructions.set(InstrToDFSNum(Mapped));
2067 assert(User && To != User);
2068 if (isa<Instruction>(To))
2069 AdditionalUsers[To].insert(User);
2072 void NewGVN::markUsersTouched(
Value *V) {
2074 for (
auto *User : V->
users()) {
2075 assert(isa<Instruction>(User) &&
"Use of value not within an instruction?");
2076 TouchedInstructions.set(InstrToDFSNum(User));
2078 touchAndErase(AdditionalUsers, V);
2082 LLVM_DEBUG(
dbgs() <<
"Adding memory user " << *U <<
" to " << *To <<
"\n");
2083 MemoryToUsers[To].insert(U);
2086 void NewGVN::markMemoryDefTouched(
const MemoryAccess *MA) {
2087 TouchedInstructions.set(MemoryToDFSNum(MA));
2090 void NewGVN::markMemoryUsersTouched(
const MemoryAccess *MA) {
2091 if (isa<MemoryUse>(MA))
2093 for (
auto U : MA->
users())
2094 TouchedInstructions.set(MemoryToDFSNum(U));
2095 touchAndErase(MemoryToUsers, MA);
2101 if (AllTempInstructions.count(I))
2104 if (
auto *PBranch = dyn_cast<PredicateBranch>(PB))
2105 PredicateToUsers[PBranch->Condition].insert(I);
2106 else if (
auto *PAssume = dyn_cast<PredicateAssume>(PB))
2107 PredicateToUsers[PAssume->Condition].insert(I);
2111 void NewGVN::markPredicateUsersTouched(
Instruction *I) {
2112 touchAndErase(PredicateToUsers, I);
2116 void NewGVN::markMemoryLeaderChangeTouched(CongruenceClass *CC) {
2117 for (
auto M : CC->memory())
2118 markMemoryDefTouched(M);
2123 void NewGVN::markValueLeaderChangeTouched(CongruenceClass *CC) {
2124 for (
auto M : *CC) {
2125 if (
auto *I = dyn_cast<Instruction>(M))
2126 TouchedInstructions.set(InstrToDFSNum(I));
2127 LeaderChanges.insert(M);
2133 template <
class T,
class Range>
2134 T *NewGVN::getMinDFSOfRange(
const Range &
R)
const {
2135 std::pair<T *, unsigned> MinDFS = {
nullptr, ~0U};
2136 for (
const auto X : R) {
2137 auto DFSNum = InstrToDFSNum(
X);
2138 if (DFSNum < MinDFS.second)
2139 MinDFS = {
X, DFSNum};
2141 return MinDFS.first;
2147 const MemoryAccess *NewGVN::getNextMemoryLeader(CongruenceClass *CC)
const {
2151 assert(!CC->definesNoMemory() &&
"Can't get next leader if there is none");
2152 if (CC->getStoreCount() > 0) {
2153 if (
auto *NL = dyn_cast_or_null<StoreInst>(CC->getNextLeader().first))
2154 return getMemoryAccess(NL);
2157 *CC, [&](
const Value *V) {
return isa<StoreInst>(V); }));
2158 return getMemoryAccess(cast<StoreInst>(V));
2160 assert(CC->getStoreCount() == 0);
2164 if (CC->memory_size() == 1)
2165 return *CC->memory_begin();
2166 return getMinDFSOfRange<const MemoryPhi>(CC->memory());
2172 Value *NewGVN::getNextValueLeader(CongruenceClass *CC)
const {
2177 if (CC->size() == 1 || CC == TOPClass) {
2178 return *(CC->begin());
2179 }
else if (CC->getNextLeader().first) {
2180 ++NumGVNAvoidedSortedLeaderChanges;
2181 return CC->getNextLeader().first;
2183 ++NumGVNSortedLeaderChanges;
2187 return getMinDFSOfRange<Value>(*CC);
2200 void NewGVN::moveMemoryToNewCongruenceClass(
Instruction *I,
2202 CongruenceClass *OldClass,
2203 CongruenceClass *NewClass) {
2206 assert((!InstMA || !OldClass->getMemoryLeader() ||
2207 OldClass->getLeader() != I ||
2208 MemoryAccessToClass.lookup(OldClass->getMemoryLeader()) ==
2209 MemoryAccessToClass.lookup(InstMA)) &&
2210 "Representative MemoryAccess mismatch");
2212 if (!NewClass->getMemoryLeader()) {
2214 assert(NewClass->size() == 1 ||
2215 (isa<StoreInst>(
I) && NewClass->getStoreCount() == 1));
2216 NewClass->setMemoryLeader(InstMA);
2219 << NewClass->getID()
2220 <<
" due to new memory instruction becoming leader\n");
2221 markMemoryLeaderChangeTouched(NewClass);
2223 setMemoryClass(InstMA, NewClass);
2225 if (OldClass->getMemoryLeader() == InstMA) {
2226 if (!OldClass->definesNoMemory()) {
2227 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
2229 << OldClass->getID() <<
" to " 2230 << *OldClass->getMemoryLeader()
2231 <<
" due to removal of old leader " << *InstMA <<
"\n");
2232 markMemoryLeaderChangeTouched(OldClass);
2234 OldClass->setMemoryLeader(
nullptr);
2241 CongruenceClass *OldClass,
2242 CongruenceClass *NewClass) {
2243 if (I == OldClass->getNextLeader().first)
2244 OldClass->resetNextLeader();
2247 NewClass->insert(I);
2249 if (NewClass->getLeader() !=
I)
2250 NewClass->addPossibleNextLeader({I, InstrToDFSNum(I)});
2252 if (
auto *SI = dyn_cast<StoreInst>(I)) {
2253 OldClass->decStoreCount();
2261 if (NewClass->getStoreCount() == 0 && !NewClass->getStoredValue()) {
2264 if (
auto *SE = dyn_cast<StoreExpression>(E)) {
2265 NewClass->setStoredValue(SE->getStoredValue());
2266 markValueLeaderChangeTouched(NewClass);
2269 << NewClass->getID() <<
" from " 2270 << *NewClass->getLeader() <<
" to " << *SI
2271 <<
" because store joined class\n");
2274 NewClass->setLeader(SI);
2278 NewClass->incStoreCount();
2284 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
2286 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
2287 ValueToClass[
I] = NewClass;
2289 if (OldClass->empty() && OldClass != TOPClass) {
2290 if (OldClass->getDefiningExpr()) {
2291 LLVM_DEBUG(
dbgs() <<
"Erasing expression " << *OldClass->getDefiningExpr()
2292 <<
" from table\n");
2295 auto Iter = ExpressionToClass.find_as(
2297 if (Iter != ExpressionToClass.end())
2298 ExpressionToClass.erase(Iter);
2299 #ifdef EXPENSIVE_CHECKS 2301 (*OldClass->getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2302 "We erased the expression we just inserted, which should not happen");
2305 }
else if (OldClass->getLeader() ==
I) {
2310 << OldClass->getID() <<
"\n");
2311 ++NumGVNLeaderChanges;
2316 if (OldClass->getStoreCount() == 0) {
2317 if (OldClass->getStoredValue())
2318 OldClass->setStoredValue(
nullptr);
2320 OldClass->setLeader(getNextValueLeader(OldClass));
2321 OldClass->resetNextLeader();
2322 markValueLeaderChangeTouched(OldClass);
2328 void NewGVN::markPhiOfOpsChanged(
const Expression *E) {
2329 touchAndErase(ExpressionToPhiOfOps, E);
2337 CongruenceClass *IClass = ValueToClass.lookup(I);
2338 assert(IClass &&
"Should have found a IClass");
2340 assert(!IClass->isDead() &&
"Found a dead class");
2342 CongruenceClass *EClass =
nullptr;
2343 if (
const auto *VE = dyn_cast<VariableExpression>(E)) {
2344 EClass = ValueToClass.lookup(VE->getVariableValue());
2345 }
else if (isa<DeadExpression>(E)) {
2349 auto lookupResult = ExpressionToClass.insert({
E,
nullptr});
2352 if (lookupResult.second) {
2353 CongruenceClass *NewClass = createCongruenceClass(
nullptr, E);
2354 auto place = lookupResult.first;
2355 place->second = NewClass;
2358 if (
const auto *CE = dyn_cast<ConstantExpression>(E)) {
2359 NewClass->setLeader(CE->getConstantValue());
2360 }
else if (
const auto *SE = dyn_cast<StoreExpression>(E)) {
2362 NewClass->setLeader(SI);
2363 NewClass->setStoredValue(SE->getStoredValue());
2367 NewClass->setLeader(I);
2369 assert(!isa<VariableExpression>(E) &&
2370 "VariableExpression should have been handled already");
2374 <<
" using expression " << *E <<
" at " 2375 << NewClass->getID() <<
" and leader " 2376 << *(NewClass->getLeader()));
2377 if (NewClass->getStoredValue())
2379 << *(NewClass->getStoredValue()));
2382 EClass = lookupResult.first->second;
2383 if (isa<ConstantExpression>(E))
2384 assert((isa<Constant>(EClass->getLeader()) ||
2385 (EClass->getStoredValue() &&
2386 isa<Constant>(EClass->getStoredValue()))) &&
2387 "Any class with a constant expression should have a " 2390 assert(EClass &&
"Somehow don't have an eclass");
2392 assert(!EClass->isDead() &&
"We accidentally looked up a dead class");
2395 bool ClassChanged = IClass != EClass;
2396 bool LeaderChanged = LeaderChanges.erase(I);
2397 if (ClassChanged || LeaderChanged) {
2398 LLVM_DEBUG(
dbgs() <<
"New class " << EClass->getID() <<
" for expression " 2401 moveValueToNewCongruenceClass(I, E, IClass, EClass);
2402 markPhiOfOpsChanged(E);
2405 markUsersTouched(I);
2407 markMemoryUsersTouched(MA);
2408 if (
auto *CI = dyn_cast<CmpInst>(I))
2409 markPredicateUsersTouched(CI);
2415 if (ClassChanged && isa<StoreInst>(I)) {
2416 auto *OldE = ValueToExpression.lookup(I);
2419 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2423 if (Iter != ExpressionToClass.end())
2424 ExpressionToClass.erase(Iter);
2427 ValueToExpression[
I] =
E;
2434 if (ReachableEdges.insert({From, To}).second) {
2436 if (ReachableBlocks.insert(To).second) {
2438 <<
" marked reachable\n");
2439 const auto &InstRange = BlockInstRange.lookup(To);
2440 TouchedInstructions.set(InstRange.first, InstRange.second);
2443 <<
" was reachable, but new edge {" 2445 <<
"} to it found\n");
2452 TouchedInstructions.set(InstrToDFSNum(MemPhi));
2457 for (
auto InstNum : RevisitOnReachabilityChange[To])
2458 TouchedInstructions.set(InstNum);
2465 Value *NewGVN::findConditionEquivalence(
Value *Cond)
const {
2466 auto Result = lookupOperandLeader(Cond);
2467 return isa<Constant>(Result) ? Result :
nullptr;
2476 Value *CondEvaluated = findConditionEquivalence(Cond);
2477 if (!CondEvaluated) {
2478 if (
auto *I = dyn_cast<Instruction>(Cond)) {
2480 if (
const auto *CE = dyn_cast<ConstantExpression>(E)) {
2481 CondEvaluated = CE->getConstantValue();
2483 }
else if (isa<ConstantInt>(Cond)) {
2484 CondEvaluated = Cond;
2488 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2491 <<
" evaluated to true\n");
2492 updateReachableEdge(B, TrueSucc);
2493 }
else if (CI->
isZero()) {
2495 <<
" evaluated to false\n");
2496 updateReachableEdge(B, FalseSucc);
2499 updateReachableEdge(B, TrueSucc);
2500 updateReachableEdge(B, FalseSucc);
2502 }
else if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
2506 Value *SwitchCond = SI->getCondition();
2507 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
2509 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
2510 auto *CondVal = cast<ConstantInt>(CondEvaluated);
2512 auto Case = *SI->findCaseValue(CondVal);
2513 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
2517 updateReachableEdge(B, SI->getDefaultDest());
2521 BasicBlock *TargetBlock = Case.getCaseSuccessor();
2522 updateReachableEdge(B, TargetBlock);
2526 updateReachableEdge(B, TargetBlock);
2534 updateReachableEdge(B, TargetBlock);
2540 auto *MA = getMemoryAccess(TI);
2541 if (MA && !isa<MemoryUse>(MA)) {
2542 auto *CC = ensureLeaderOfMemoryClass(MA);
2543 if (setMemoryClass(MA, CC))
2544 markMemoryUsersTouched(MA);
2551 InstrDFS.erase(PHITemp);
2554 TempToBlock.erase(PHITemp);
2555 RealToTemp.erase(I);
2565 InstrDFS[
Op] = InstrToDFSNum(ExistingValue);
2566 AllTempInstructions.insert(Op);
2567 TempToBlock[
Op] = BB;
2568 RealToTemp[ExistingValue] =
Op;
2571 for (
auto *U : ExistingValue->
users())
2572 if (
auto *UI = dyn_cast<Instruction>(U))
2573 PHINodeUses.insert(UI);
2579 return isa<BinaryOperator>(
I) || isa<SelectInst>(I) || isa<CmpInst>(
I) ||
2583 bool NewGVN::OpIsSafeForPHIOfOpsHelper(
2588 if (!isa<Instruction>(V))
2590 auto OISIt = OpSafeForPHIOfOps.find(V);
2591 if (OISIt != OpSafeForPHIOfOps.end())
2592 return OISIt->second;
2596 if (DT->properlyDominates(getBlockForValue(V), PHIBlock)) {
2597 OpSafeForPHIOfOps.insert({V,
true});
2601 if (isa<PHINode>(V) && getBlockForValue(V) == PHIBlock) {
2602 OpSafeForPHIOfOps.insert({V,
false});
2606 auto *OrigI = cast<Instruction>(V);
2608 if (!isa<Instruction>(Op))
2611 auto OISIt = OpSafeForPHIOfOps.find(OrigI);
2612 if (OISIt != OpSafeForPHIOfOps.end()) {
2613 if (!OISIt->second) {
2614 OpSafeForPHIOfOps.insert({V,
false});
2619 if (!Visited.
insert(Op).second)
2621 Worklist.
push_back(cast<Instruction>(Op));
2633 bool NewGVN::OpIsSafeForPHIOfOps(
Value *V,
const BasicBlock *PHIBlock,
2636 if (!OpIsSafeForPHIOfOpsHelper(V, PHIBlock, Visited, Worklist))
2638 while (!Worklist.
empty()) {
2640 if (!OpIsSafeForPHIOfOpsHelper(I, PHIBlock, Visited, Worklist))
2643 OpSafeForPHIOfOps.insert({V,
true});
2656 unsigned IDFSNum = InstrToDFSNum(OrigInst);
2658 AllTempInstructions.insert(TransInst);
2662 TempToBlock.insert({TransInst, PredBB});
2663 InstrDFS.insert({TransInst, IDFSNum});
2665 const Expression *E = performSymbolicEvaluation(TransInst, Visited);
2666 InstrDFS.erase(TransInst);
2667 AllTempInstructions.erase(TransInst);
2668 TempToBlock.erase(TransInst);
2670 TempToMemory.erase(TransInst);
2673 auto *FoundVal = findPHIOfOpsLeader(E, OrigInst, PredBB);
2675 ExpressionToPhiOfOps[
E].insert(OrigInst);
2676 LLVM_DEBUG(
dbgs() <<
"Cannot find phi of ops operand for " << *TransInst
2680 if (
auto *SI = dyn_cast<StoreInst>(FoundVal))
2693 if (!Visited.
insert(I).second)
2699 if (!isCycleFree(I))
2706 auto *MemAccess = getMemoryAccess(I);
2710 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2721 for (
auto *Op : Ops) {
2722 if (!isa<PHINode>(Op)) {
2723 auto *ValuePHI = RealToTemp.lookup(Op);
2729 OpPHI = cast<PHINode>(
Op);
2730 if (!SamePHIBlock) {
2731 SamePHIBlock = getBlockForValue(OpPHI);
2732 }
else if (SamePHIBlock != getBlockForValue(OpPHI)) {
2735 <<
"PHIs for operands are not all in the same block, aborting\n");
2750 auto *PHIBlock = getBlockForValue(OpPHI);
2751 RevisitOnReachabilityChange[PHIBlock].reset(InstrToDFSNum(I));
2752 for (
unsigned PredNum = 0; PredNum < OpPHI->
getNumOperands(); ++PredNum) {
2754 Value *FoundVal =
nullptr;
2758 if (ReachableEdges.count({PredBB, PHIBlock})) {
2763 TempToMemory.insert({ValueOp, MemAccess});
2764 bool SafeForPHIOfOps =
true;
2766 for (
auto &Op : ValueOp->
operands()) {
2767 auto *OrigOp = &*
Op;
2770 if (isa<PHINode>(Op)) {
2772 if (Op != OrigOp && Op != I)
2774 }
else if (
auto *ValuePHI = RealToTemp.lookup(Op)) {
2775 if (getBlockForValue(ValuePHI) == PHIBlock)
2781 (Op != OrigOp || OpIsSafeForPHIOfOps(Op, PHIBlock, VisitedOps));
2788 FoundVal = !SafeForPHIOfOps ? nullptr
2789 : findLeaderForInst(ValueOp, Visited,
2790 MemAccess, I, PredBB);
2795 if (SafeForPHIOfOps)
2796 for (
auto Dep : CurrentDeps)
2797 addAdditionalUsers(Dep, I);
2803 LLVM_DEBUG(
dbgs() <<
"Skipping phi of ops operand for incoming block " 2805 <<
" because the block is unreachable\n");
2807 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
2811 LLVM_DEBUG(
dbgs() <<
"Found phi of ops operand " << *FoundVal <<
" in " 2814 for (
auto Dep : Deps)
2815 addAdditionalUsers(Dep, I);
2817 auto *E = performSymbolicPHIEvaluation(PHIOps, I, PHIBlock);
2818 if (isa<ConstantExpression>(E) || isa<VariableExpression>(E)) {
2821 <<
"Not creating real PHI of ops because it simplified to existing " 2822 "value or constant\n");
2825 auto *ValuePHI = RealToTemp.lookup(I);
2826 bool NewPHI =
false;
2830 addPhiOfOps(ValuePHI, PHIBlock, I);
2832 NumGVNPHIOfOpsCreated++;
2835 for (
auto PHIOp : PHIOps)
2836 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2838 TempToBlock[ValuePHI] = PHIBlock;
2840 for (
auto PHIOp : PHIOps) {
2841 ValuePHI->setIncomingValue(i, PHIOp.first);
2842 ValuePHI->setIncomingBlock(i, PHIOp.second);
2846 RevisitOnReachabilityChange[PHIBlock].set(InstrToDFSNum(I));
2847 LLVM_DEBUG(
dbgs() <<
"Created phi of ops " << *ValuePHI <<
" for " << *I
2856 void NewGVN::initializeCongruenceClasses(
Function &F) {
2857 NextCongruenceNum = 0;
2867 TOPClass = createCongruenceClass(
nullptr,
nullptr);
2868 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
2870 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2871 createMemoryClass(MSSA->getLiveOnEntryDef());
2873 for (
auto DTN :
nodes(DT)) {
2879 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
2880 if (MemoryBlockDefs)
2881 for (
const auto &
Def : *MemoryBlockDefs) {
2882 MemoryAccessToClass[&
Def] = TOPClass;
2887 TOPClass->memory_insert(MP);
2888 MemoryPhiState.insert({MP, MPS_TOP});
2891 if (MD && isa<StoreInst>(MD->getMemoryInst()))
2892 TOPClass->incStoreCount();
2898 for (
auto &I : *BB) {
2899 if (isa<PHINode>(&I))
2900 for (
auto *U : I.
users())
2901 if (
auto *UInst = dyn_cast<Instruction>(U))
2903 PHINodeUses.insert(UInst);
2908 TOPClass->insert(&I);
2909 ValueToClass[&
I] = TOPClass;
2914 for (
auto &FA : F.
args())
2915 createSingletonCongruenceClass(&FA);
2918 void NewGVN::cleanupTables() {
2919 for (
unsigned i = 0,
e = CongruenceClasses.size(); i !=
e; ++i) {
2920 LLVM_DEBUG(
dbgs() <<
"Congruence class " << CongruenceClasses[i]->getID()
2921 <<
" has " << CongruenceClasses[i]->
size()
2925 delete CongruenceClasses[i];
2926 CongruenceClasses[i] =
nullptr;
2931 AllTempInstructions.end());
2932 AllTempInstructions.
clear();
2936 for (
auto *I : TempInst) {
2940 while (!TempInst.empty()) {
2941 auto *I = TempInst.back();
2942 TempInst.pop_back();
2946 ValueToClass.clear();
2947 ArgRecycler.clear(ExpressionAllocator);
2948 ExpressionAllocator.Reset();
2949 CongruenceClasses.clear();
2950 ExpressionToClass.clear();
2951 ValueToExpression.clear();
2953 AdditionalUsers.clear();
2954 ExpressionToPhiOfOps.clear();
2955 TempToBlock.clear();
2956 TempToMemory.clear();
2957 PHINodeUses.clear();
2958 OpSafeForPHIOfOps.clear();
2959 ReachableBlocks.clear();
2960 ReachableEdges.clear();
2962 ProcessedCount.clear();
2965 InstructionsToErase.clear();
2967 BlockInstRange.clear();
2968 TouchedInstructions.clear();
2969 MemoryAccessToClass.clear();
2970 PredicateToUsers.clear();
2971 MemoryToUsers.clear();
2972 RevisitOnReachabilityChange.clear();
2977 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(
BasicBlock *B,
2979 unsigned End = Start;
2981 InstrDFS[MemPhi] = End++;
2982 DFSToInstr.emplace_back(MemPhi);
2986 for (
auto &I : *B) {
2992 LLVM_DEBUG(
dbgs() <<
"Skipping trivially dead instruction " << I <<
"\n");
2993 markInstructionForDeletion(&I);
2996 if (isa<PHINode>(&I))
2997 RevisitOnReachabilityChange[
B].set(End);
2998 InstrDFS[&
I] = End++;
2999 DFSToInstr.emplace_back(&I);
3005 return std::make_pair(Start, End);
3008 void NewGVN::updateProcessedCount(
const Value *V) {
3010 if (ProcessedCount.count(V) == 0) {
3011 ProcessedCount.insert({V, 1});
3013 ++ProcessedCount[V];
3014 assert(ProcessedCount[V] < 100 &&
3015 "Seem to have processed the same Value a lot");
3021 void NewGVN::valueNumberMemoryPhi(
MemoryPhi *MP) {
3028 return cast<MemoryAccess>(U) != MP &&
3029 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
3030 ReachableEdges.count({MP->getIncomingBlock(U), PHIBlock});
3035 if (Filtered.begin() == Filtered.end()) {
3036 if (setMemoryClass(MP, TOPClass))
3037 markMemoryUsersTouched(MP);
3043 auto LookupFunc = [&](
const Use &U) {
3044 return lookupMemoryLeader(cast<MemoryAccess>(U));
3046 auto MappedBegin =
map_iterator(Filtered.begin(), LookupFunc);
3047 auto MappedEnd =
map_iterator(Filtered.end(), LookupFunc);
3051 const auto *AllSameValue = *MappedBegin;
3054 MappedBegin, MappedEnd,
3055 [&AllSameValue](
const MemoryAccess *V) {
return V == AllSameValue; });
3058 LLVM_DEBUG(
dbgs() <<
"Memory Phi value numbered to " << *AllSameValue
3067 CongruenceClass *CC =
3068 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
3069 auto OldState = MemoryPhiState.lookup(MP);
3070 assert(OldState != MPS_Invalid &&
"Invalid memory phi state");
3071 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
3072 MemoryPhiState[MP] = NewState;
3073 if (setMemoryClass(MP, CC) || OldState != NewState)
3074 markMemoryUsersTouched(MP);
3079 void NewGVN::valueNumberInstruction(
Instruction *I) {
3085 Symbolized = performSymbolicEvaluation(I, Visited);
3087 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
3088 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
3089 auto *PHIE = makePossiblePHIOfOps(I, Visited);
3094 }
else if (
auto *Op = RealToTemp.lookup(I)) {
3095 removePhiOfOps(I, Op);
3104 if (Symbolized ==
nullptr)
3105 Symbolized = createUnknownExpression(I);
3106 performCongruenceFinding(I, Symbolized);
3112 auto *Symbolized = createUnknownExpression(I);
3113 performCongruenceFinding(I, Symbolized);
3115 processOutgoingEdges(I, I->
getParent());
3121 bool NewGVN::singleReachablePHIPath(
3124 if (First == Second)
3126 if (MSSA->isLiveOnEntryDef(First))
3134 if (Visited.
count(First))
3138 const auto *EndDef = First;
3140 if (ChainDef == Second)
3142 if (MSSA->isLiveOnEntryDef(ChainDef))
3146 auto *MP = cast<MemoryPhi>(EndDef);
3147 auto ReachableOperandPred = [&](
const Use &U) {
3150 auto FilteredPhiArgs =
3153 llvm::copy(FilteredPhiArgs, std::back_inserter(OperandList));
3156 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
3165 void NewGVN::verifyMemoryCongruency()
const {
3168 for (
const auto *CC : CongruenceClasses) {
3169 if (CC == TOPClass || CC->isDead())
3171 if (CC->getStoreCount() != 0) {
3172 assert((CC->getStoredValue() || !isa<StoreInst>(CC->getLeader())) &&
3173 "Any class with a store as a leader should have a " 3174 "representative stored value");
3175 assert(CC->getMemoryLeader() &&
3176 "Any congruence class with a store should have a " 3177 "representative access");
3180 if (CC->getMemoryLeader())
3181 assert(MemoryAccessToClass.lookup(CC->getMemoryLeader()) == CC &&
3182 "Representative MemoryAccess does not appear to be reverse " 3184 for (
auto M : CC->memory())
3185 assert(MemoryAccessToClass.lookup(M) == CC &&
3186 "Memory member does not appear to be reverse mapped properly");
3194 auto ReachableAccessPred =
3195 [&](
const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
3196 bool Result = ReachableBlocks.count(Pair.first->getBlock());
3197 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
3198 MemoryToDFSNum(Pair.first) == 0)
3200 if (
auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
3205 if (
auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
3206 for (
auto &U : MemPHI->incoming_values()) {
3207 if (
auto *I = dyn_cast<Instruction>(&*U)) {
3219 for (
auto KV : Filtered) {
3220 if (
auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
3222 if (FirstMUD && SecondMUD) {
3224 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
3225 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
3226 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
3227 "The instructions for these memory operations should have " 3228 "been in the same congruence class or reachable through" 3229 "a single argument phi");
3231 }
else if (
auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
3234 auto ReachableOperandPred = [&](
const Use &U) {
3235 return ReachableEdges.count(
3236 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
3241 auto FilteredPhiArgs =
3245 std::back_inserter(PhiOpClasses), [&](
const Use &U) {
3246 const MemoryDef *MD = cast<MemoryDef>(U);
3250 "All MemoryPhi arguments should be in the same class");
3259 void NewGVN::verifyIterationSettled(
Function &F) {
3269 std::map<const Value *, CongruenceClass> BeforeIteration;
3271 for (
auto &KV : ValueToClass) {
3272 if (
auto *I = dyn_cast<Instruction>(KV.first))
3274 if (InstrToDFSNum(I) == 0)
3276 BeforeIteration.insert({KV.first, *KV.second});
3279 TouchedInstructions.set();
3280 TouchedInstructions.reset(0);
3281 iterateTouchedInstructions();
3284 for (
const auto &KV : ValueToClass) {
3285 if (
auto *I = dyn_cast<Instruction>(KV.first))
3287 if (InstrToDFSNum(I) == 0)
3291 auto *BeforeCC = &BeforeIteration.
find(KV.first)->second;
3292 auto *AfterCC = KV.second;
3295 if (!EqualClasses.
count({BeforeCC, AfterCC})) {
3296 assert(BeforeCC->isEquivalentTo(AfterCC) &&
3297 "Value number changed after main loop completed!");
3298 EqualClasses.
insert({BeforeCC, AfterCC});
3309 void NewGVN::verifyStoreExpressions()
const {
3314 std::pair<
const Value *,
3315 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3317 for (
const auto &KV : ExpressionToClass) {
3318 if (
auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3320 auto Res = StoreExpressionSet.insert(
3321 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3322 SE->getStoredValue())});
3323 bool Okay = Res.second;
3328 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3329 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3330 lookupOperandLeader(SE->getStoredValue()));
3331 assert(Okay &&
"Stored expression conflict exists in expression table");
3332 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3333 assert(ValueExpr && ValueExpr->equals(*SE) &&
3334 "StoreExpression in ExpressionToClass is not latest " 3335 "StoreExpression for value");
3344 void NewGVN::iterateTouchedInstructions() {
3345 unsigned int Iterations = 0;
3347 int FirstInstr = TouchedInstructions.find_first();
3349 if (FirstInstr == -1)
3351 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
3352 while (TouchedInstructions.any()) {
3358 for (
unsigned InstrNum : TouchedInstructions.set_bits()) {
3362 if (InstrNum == 0) {
3363 TouchedInstructions.reset(InstrNum);
3367 Value *V = InstrFromDFSNum(InstrNum);
3368 const BasicBlock *CurrBlock = getBlockForValue(V);
3371 if (CurrBlock != LastBlock) {
3372 LastBlock = CurrBlock;
3373 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3374 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3377 if (!BlockReachable) {
3378 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3381 <<
" because it is unreachable\n");
3384 updateProcessedCount(CurrBlock);
3388 TouchedInstructions.reset(InstrNum);
3390 if (
auto *MP = dyn_cast<MemoryPhi>(V)) {
3392 valueNumberMemoryPhi(MP);
3393 }
else if (
auto *I = dyn_cast<Instruction>(V)) {
3394 valueNumberInstruction(I);
3398 updateProcessedCount(V);
3401 NumGVNMaxIterations =
std::max(NumGVNMaxIterations.getValue(), Iterations);
3405 bool NewGVN::runGVN() {
3408 bool Changed =
false;
3410 MSSAWalker = MSSA->getWalker();
3411 SingletonDeadExpression =
new (ExpressionAllocator)
DeadExpression();
3415 unsigned ICount = 1;
3417 DFSToInstr.emplace_back(
nullptr);
3427 unsigned Counter = 0;
3428 for (
auto &B : RPOT) {
3429 auto *Node = DT->getNode(B);
3430 assert(Node &&
"RPO and Dominator tree should have same reachability");
3431 RPOOrdering[Node] = ++Counter;
3434 for (
auto &B : RPOT) {
3435 auto *Node = DT->getNode(B);
3436 if (Node->getChildren().size() > 1)
3439 return RPOOrdering[
A] < RPOOrdering[
B];
3446 const auto &BlockRange = assignDFSNumbers(B, ICount);
3447 BlockInstRange.insert({
B, BlockRange});
3448 ICount += BlockRange.second - BlockRange.first;
3450 initializeCongruenceClasses(F);
3452 TouchedInstructions.resize(ICount);
3456 ExpressionToClass.reserve(ICount);
3459 const auto &InstRange = BlockInstRange.lookup(&F.
getEntryBlock());
3460 TouchedInstructions.set(InstRange.first, InstRange.second);
3462 <<
" marked reachable\n");
3465 iterateTouchedInstructions();
3466 verifyMemoryCongruency();
3467 verifyIterationSettled(F);
3468 verifyStoreExpressions();
3470 Changed |= eliminateInstructions(F);
3473 for (
Instruction *ToErase : InstructionsToErase) {
3474 if (!ToErase->use_empty())
3477 assert(ToErase->getParent() &&
3478 "BB containing ToErase deleted unexpectedly!");
3479 ToErase->eraseFromParent();
3481 Changed |= !InstructionsToErase.empty();
3484 auto UnreachableBlockPred = [&](
const BasicBlock &BB) {
3485 return !ReachableBlocks.count(&BB);
3490 <<
" is unreachable\n");
3491 deleteInstructionsInBlock(&BB);
3549 return std::tie(DFSIn, DFSOut, LocalNum, Def, U) <
3560 void NewGVN::convertClassToDFSOrdered(
3564 for (
auto D : Dense) {
3569 assert(BB &&
"Should have figured out a basic block for value");
3577 if (
auto *SI = dyn_cast<StoreInst>(
D)) {
3589 "The dense set member should always be an instruction");
3594 if (
auto *PN = RealToTemp.lookup(Def)) {
3596 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3605 unsigned int UseCount = 0;
3607 for (
auto &U : Def->
uses()) {
3608 if (
auto *I = dyn_cast<Instruction>(U.getUser())) {
3610 if (InstructionsToErase.count(I))
3615 if (
auto *
P = dyn_cast<PHINode>(I)) {
3616 IBlock =
P->getIncomingBlock(U);
3619 VDUse.
LocalNum = InstrDFS.size() + 1;
3621 IBlock = getBlockForValue(I);
3627 if (ReachableBlocks.count(IBlock) == 0)
3643 ProbablyDead.
insert(Def);
3645 UseCounts[
Def] = UseCount;
3651 void NewGVN::convertClassToLoadsAndStores(
3652 const CongruenceClass &Dense,
3654 for (
auto D : Dense) {
3655 if (!isa<LoadInst>(
D) && !isa<StoreInst>(
D))
3666 if (
auto *I = dyn_cast<Instruction>(
D))
3680 void NewGVN::deleteInstructionsInBlock(
BasicBlock *BB) {
3682 ++NumGVNBlocksDeleted;
3686 auto StartPoint = BB->
rbegin();
3694 if (isa<LandingPadInst>(Inst))
3698 ++NumGVNInstrDeleted;
3707 void NewGVN::markInstructionForDeletion(
Instruction *I) {
3709 InstructionsToErase.insert(I);
3713 LLVM_DEBUG(
dbgs() <<
"Replacing " << *I <<
" with " << *V <<
"\n");
3717 markInstructionForDeletion(I);
3724 class ValueDFSStack {
3726 Value *back()
const {
return ValueStack.back(); }
3727 std::pair<int, int> dfs_back()
const {
return DFSStack.back(); }
3729 void push_back(
Value *V,
int DFSIn,
int DFSOut) {
3730 ValueStack.emplace_back(V);
3731 DFSStack.emplace_back(DFSIn, DFSOut);
3734 bool empty()
const {
return DFSStack.empty(); }
3736 bool isInScope(
int DFSIn,
int DFSOut)
const {
3739 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3742 void popUntilDFSScope(
int DFSIn,
int DFSOut) {
3745 assert(ValueStack.size() == DFSStack.size() &&
3746 "Mismatch between ValueStack and DFSStack");
3748 !DFSStack.empty() &&
3749 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3750 DFSStack.pop_back();
3751 ValueStack.pop_back();
3763 CongruenceClass *NewGVN::getClassForExpression(
const Expression *E)
const {
3764 if (
auto *VE = dyn_cast<VariableExpression>(E))
3765 return ValueToClass.lookup(VE->getVariableValue());
3766 else if (isa<DeadExpression>(E))
3768 return ExpressionToClass.lookup(E);
3777 if (
auto *CE = dyn_cast<ConstantExpression>(E))
3778 return CE->getConstantValue();
3779 if (
auto *VE = dyn_cast<VariableExpression>(E)) {
3780 auto *V = VE->getVariableValue();
3782 return VE->getVariableValue();
3785 auto *CC = getClassForExpression(E);
3789 return CC->getLeader();
3791 for (
auto Member : *CC) {
3793 if (MemberInst == OrigInst)
3798 if (DT->dominates(getBlockForValue(MemberInst), BB))
3804 bool NewGVN::eliminateInstructions(
Function &F) {
3828 bool AnythingReplaced =
false;
3832 DT->updateDFSNumbers();
3838 if (!ReachableEdges.count({PHI->getIncomingBlock(Operand), BB})) {
3842 <<
" with undef due to it being unreachable\n");
3856 for (
auto &KV : ReachableEdges)
3857 ReachablePredCount[KV.getEnd()]++;
3858 for (
auto &BBPair : RevisitOnReachabilityChange) {
3859 for (
auto InstNum : BBPair.second) {
3860 auto *Inst = InstrFromDFSNum(InstNum);
3862 PHI = PHI ? PHI : dyn_cast_or_null<PHINode>(RealToTemp.lookup(Inst));
3865 auto *BB = BBPair.first;
3866 if (ReachablePredCount.
lookup(BB) != PHI->getNumIncomingValues())
3867 ReplaceUnreachablePHIArgs(PHI, BB);
3873 for (
auto *CC :
reverse(CongruenceClasses)) {
3874 LLVM_DEBUG(
dbgs() <<
"Eliminating in congruence class " << CC->getID()
3880 if (CC->isDead() || CC->empty())
3883 if (CC == TOPClass) {
3884 for (
auto M : *CC) {
3885 auto *VTE = ValueToExpression.lookup(M);
3886 if (VTE && isa<DeadExpression>(VTE))
3887 markInstructionForDeletion(cast<Instruction>(M));
3888 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3889 InstructionsToErase.count(cast<Instruction>(M))) &&
3890 "Everything in TOP should be unreachable or dead at this " 3896 assert(CC->getLeader() &&
"We should have had a leader");
3902 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
3905 for (
auto M : *CC) {
3908 if (Member == Leader || !isa<Instruction>(Member) ||
3910 MembersLeft.
insert(Member);
3913 LLVM_DEBUG(
dbgs() <<
"Found replacement " << *(Leader) <<
" for " 3914 << *Member <<
"\n");
3915 auto *I = cast<Instruction>(Member);
3916 assert(Leader != I &&
"About to accidentally remove our leader");
3917 replaceInstruction(I, Leader);
3918 AnythingReplaced =
true;
3920 CC->swap(MembersLeft);
3923 if (CC->size() != 1 || RealToTemp.count(Leader)) {
3928 ValueDFSStack EliminationStack;
3932 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
3936 for (
auto &VD : DFSOrderedSet) {
3937 int MemberDFSIn = VD.DFSIn;
3938 int MemberDFSOut = VD.DFSOut;
3940 bool FromStore = VD.Def.getInt();
3945 auto *DefInst = dyn_cast_or_null<Instruction>(
Def);
3946 if (DefInst && AllTempInstructions.count(DefInst)) {
3947 auto *PN = cast<PHINode>(DefInst);
3952 AllTempInstructions.erase(PN);
3953 auto *DefBlock = getBlockForValue(Def);
3957 PN->insertBefore(&DefBlock->front());
3959 NumGVNPHIOfOpsEliminations++;
3962 if (EliminationStack.empty()) {
3966 << EliminationStack.dfs_back().first <<
"," 3967 << EliminationStack.dfs_back().second <<
")\n");
3970 LLVM_DEBUG(
dbgs() <<
"Current DFS numbers are (" << MemberDFSIn <<
"," 3971 << MemberDFSOut <<
")\n");
3985 bool ShouldPush = Def && EliminationStack.empty();
3987 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3989 if (OutOfScope || ShouldPush) {
3991 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3992 bool ShouldPush = Def && EliminationStack.empty();
3994 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
4013 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
4014 isa<Instruction>(
Def) && !FromStore)
4015 markInstructionForDeletion(cast<Instruction>(Def));
4021 assert(isa<Instruction>(U->get()) &&
4022 "Current def should have been an instruction");
4023 assert(isa<Instruction>(U->getUser()) &&
4024 "Current user should have been an instruction");
4030 Instruction *InstUse = cast<Instruction>(U->getUser());
4031 if (InstructionsToErase.count(InstUse)) {
4032 auto &UseCount = UseCounts[U->get()];
4033 if (--UseCount == 0) {
4034 ProbablyDead.
insert(cast<Instruction>(U->get()));
4040 if (EliminationStack.empty())
4043 Value *DominatingLeader = EliminationStack.back();
4046 bool isSSACopy = II && II->
getIntrinsicID() == Intrinsic::ssa_copy;
4048 DominatingLeader = II->getOperand(0);
4051 if (U->get() == DominatingLeader)
4054 <<
"Found replacement " << *DominatingLeader <<
" for " 4055 << *U->get() <<
" in " << *(U->getUser()) <<
"\n");
4060 auto *ReplacedInst = cast<Instruction>(U->get());
4061 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
4062 if (!PI || DominatingLeader != PI->OriginalOp)
4064 U->set(DominatingLeader);
4067 auto &LeaderUseCount = UseCounts[DominatingLeader];
4069 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
4070 ProbablyDead.
erase(cast<Instruction>(DominatingLeader));
4074 unsigned &IIUseCount = UseCounts[II];
4075 if (--IIUseCount == 0)
4079 AnythingReplaced =
true;
4086 for (
auto *I : ProbablyDead)
4088 markInstructionForDeletion(I);
4092 for (
auto *Member : *CC)
4093 if (!isa<Instruction>(Member) ||
4094 !InstructionsToErase.count(cast<Instruction>(Member)))
4095 MembersLeft.
insert(Member);
4096 CC->swap(MembersLeft);
4099 if (CC->getStoreCount() > 0) {
4100 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
4102 ValueDFSStack EliminationStack;
4103 for (
auto &VD : PossibleDeadStores) {
4104 int MemberDFSIn = VD.DFSIn;
4105 int MemberDFSOut = VD.DFSOut;
4106 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
4107 if (EliminationStack.empty() ||
4108 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
4110 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
4111 if (EliminationStack.empty()) {
4112 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
4117 if (isa<LoadInst>(Member))
4119 assert(!EliminationStack.empty());
4120 Instruction *Leader = cast<Instruction>(EliminationStack.back());
4125 <<
" that is dominated by " << *Leader <<
"\n");
4126 markInstructionForDeletion(Member);
4132 return AnythingReplaced;
4140 unsigned int NewGVN::getRank(
const Value *V)
const {
4144 if (isa<ConstantExpr>(V))
4146 if (isa<UndefValue>(V))
4148 if (isa<Constant>(V))
4150 else if (
auto *A = dyn_cast<Argument>(V))
4151 return 3 + A->getArgNo();
4155 unsigned Result = InstrToDFSNum(V);
4157 return 4 + NumFuncArgs + Result;
4164 bool NewGVN::shouldSwapOperands(
const Value *A,
const Value *B)
const {
4168 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
4199 if (skipFunction(F))
4201 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
4202 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
4203 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
4204 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
4205 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
Legacy wrapper pass to provide the GlobalsAAResult object.
void initializeNewGVNLegacyPassPass(PassRegistry &)
Value * getValueOperand()
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
static ConstantInt * getFalse(LLVMContext &Context)
reference emplace_back(ArgTypes &&... Args)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
void setInt(IntType IntVal) LLVM_LVALUE_FUNCTION
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
int analyzeLoadFromClobberingLoad(Type *LoadTy, Value *LoadPtr, LoadInst *DepLI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the load at De...
~BasicExpression() override
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
unsigned getValueID() const
Return an ID for the concrete type of this object.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
void dropAllReferences()
Drop all references to operands.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
brc_match< Cond_t, bind_ty< BasicBlock >, bind_ty< BasicBlock > > m_Br(const Cond_t &C, BasicBlock *&T, BasicBlock *&F)
static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS)
This class represents lattice values for constants.
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS)
This is the interface for a simple mod/ref and alias analysis over globals.
Represents an op.with.overflow intrinsic.
BasicBlock * getSuccessor(unsigned Idx) const
Return the specified successor. This instruction must be a terminator.
static bool okayForPHIOfOps(const Instruction *I)
Implements a dense probed hash-table based set.
void push_back(const T &Elt)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
This class represents a function call, abstracting a target machine's calling convention.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
bool isTerminator() const
1 1 1 0 True if unordered or not equal
Recycle small arrays allocated from a BumpPtrAllocator.
void deleteValue()
Delete a pointer to a generic Value.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
reverse_iterator rbegin()
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
This defines the Use class.
Constant * getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, const DataLayout &DL)
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
ExactEqualsExpression(const Expression &E)
LLVMContext & getContext() const
Get the context in which this basic block lives.
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is false when two compares have matching operands.
bool match(Val *V, const Pattern &P)
hash_code getComputedHash() const
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
static cl::opt< bool > EnablePhiOfOps("enable-phi-of-ops", cl::init(true), cl::Hidden)
Currently, the generation "phi of ops" can result in correctness issues.
~AggregateValueExpression() override
void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Value * SimplifyGEPInst(Type *SrcTy, ArrayRef< Value *> Ops, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
A Use represents the edge between a Value definition and its users.
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
hash_code getComputedHash() const
int analyzeLoadFromClobberingMemInst(Type *LoadTy, Value *LoadPtr, MemIntrinsic *DepMI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the memory int...
Constant * getConstantStoreValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
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.
static bool isImpliedTrueByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is true when two compares have matching operands.
PointerIntPair< Value *, 1, bool > Def
friend const_iterator begin(StringRef path, Style style)
Get begin iterator over path.
bool equals(const Expression &Other) const override
This file provides an implementation of debug counters.
static unsigned getHashValue(const ExactEqualsExpression &E)
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
Value * SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
Type * getType() const
All values are typed, get the type of this value.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
static bool isCounterSet(unsigned ID)
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
This is the generic walker interface for walkers of MemorySSA.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static const Expression * getEmptyKey()
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
int analyzeLoadFromClobberingStore(Type *LoadTy, Value *LoadPtr, StoreInst *DepSI, const DataLayout &DL)
This function determines whether a value for the pointer LoadPtr can be extracted from the store at D...
void setPointer(PointerTy PtrVal) LLVM_LVALUE_FUNCTION
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree...
static bool runOnFunction(Function &F, bool PostInlining)
initializer< Ty > init(const Ty &Val)
friend const_iterator end(StringRef path)
Get end iterator over path.
Value * SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q)
Given operands for a SelectInst, fold the result or return null.
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.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
MutableArrayRef - Represent a mutable reference to an array (0 or more elements consecutively in memo...
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
Allocate memory in an ever growing pool, as if by bump-pointer.
bool is_splat(R &&Range)
Wrapper function around std::equal to detect if all elements in a container are same.
static void setCounterValue(unsigned ID, int64_t Count)
size_t size() const
size - Get the array size.
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
Constant * getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
mapped_iterator< ItTy, FuncTy > map_iterator(ItTy I, FuncTy F)
A manager for alias analyses.
std::pair< iterator, bool > insert(const ValueT &V)
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
static int64_t getCounterValue(unsigned ID)
Value * SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
Represent the analysis usage information of a pass.
iterator_range< def_chain_iterator< T, true > > optimized_def_chain(T MA)
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
This file provides the interface for LLVM's Global Value Numbering pass.
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Value * getPointerOperand()
unsigned getDFSNumOut() const
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
static bool shouldExecute(unsigned CounterName)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static const Expression * getTombstoneKey()
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
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.
static bool isCopyOfAPHI(const Value *V)
void sort(IteratorTy Start, IteratorTy End)
constexpr bool empty(const T &RangeOrContainer)
Test whether RangeOrContainer is empty. Similar to C++17 std::empty.
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
This is the shared class of boolean and integer constants.
auto size(R &&Range, typename std::enable_if< std::is_same< typename std::iterator_traits< decltype(Range.begin())>::iterator_category, std::random_access_iterator_tag >::value, void >::type *=nullptr) -> decltype(std::distance(Range.begin(), Range.end()))
Get the size of a range.
void setOpcode(unsigned opcode)
BlockVerifier::State From
Align max(MaybeAlign Lhs, Align Rhs)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Provides information about what library functions are available for the current target.
An analysis that produces MemorySSA for a function.
LLVM_NODISCARD T pop_back_val()
PreservedAnalyses run(Function &F, AnalysisManager< Function > &AM)
Run the pass over the function.
BasicBlock * getBlock() const
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
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.
static bool alwaysAvailable(Value *V)
Class that has the common methods + fields of memory uses/defs.
iterator_range< user_iterator > users()
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
An opaque object representing a hash code.
bool isMallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates uninitialized memory (such ...
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
bool operator<(const ValueDFS &Other) const
Predicate getPredicate() const
Return the predicate for this instruction.
iterator_range< typename GraphTraits< GraphType >::nodes_iterator > nodes(const GraphType &G)
static Value * getCopyOf(const Value *V)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
LLVM_NODISCARD bool empty() const
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
bool isCallocLikeFn(const Value *V, const TargetLibraryInfo *TLI, bool LookThroughBitCast=false)
Tests if a value is a call or invoke to a library function that allocates zero-filled memory (such as...
static GCRegistry::Add< ErlangGC > A("erlang", "erlang-compatible garbage collector")
iterator find(const_arg_type_t< ValueT > V)
~LoadExpression() override
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
~CallExpression() override
iterator_range< value_op_iterator > operand_values()
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
Constant * ConstantFoldInstOperands(Instruction *I, ArrayRef< Constant *> Ops, const DataLayout &DL, const TargetLibraryInfo *TLI=nullptr)
ConstantFoldInstOperands - Attempt to constant fold an instruction with the specified operands...
void preserve()
Mark an analysis as preserved.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
iterator_range< filter_iterator< detail::IterOfRange< RangeT >, PredicateT > > make_filter_range(RangeT &&Range, PredicateT Pred)
Convenience function that takes a range of elements and a predicate, and return a new filter_iterator...
static std::string getBlockName(const BasicBlock *B)
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...
OutputIt transform(R &&Range, OutputIt d_first, UnaryPredicate P)
Wrapper function around std::transform to apply a function to a range and store the result elsewhere...
~StoreExpression() override
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
Value * SimplifyBinOp(unsigned Opcode, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a BinaryOperator, fold the result or return null.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
bool equals(const Expression &Other) const override
static bool isEqual(const Expression *LHS, const Expression *RHS)
static bool isCopyOfPHI(const Value *V, const PHINode *PN)
0 0 0 1 True if ordered and equal
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
~PHIExpression() override
Value * getOperand(unsigned N) const
The header file for the GVN pass that contains expression handling classes.
bool wouldInstructionBeTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction would have no side effects if it was not used...
static cl::opt< bool > EnableStoreRefinement("enable-store-refinement", cl::init(false), cl::Hidden)
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
FunctionPass * createNewGVNPass()
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
unsigned getOpcode() const
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
static unsigned getHashValue(const Expression *E)
virtual bool exactlyEquals(const Expression &Other) const
op_range incoming_values()
OutputIt copy(R &&Range, OutputIt Out)
void op_push_back(Value *Arg)
Value * getPointerOperand()
DEBUG_COUNTER(VNCounter, "newgvn-vn", "Controls which instructions are value numbered")
static IntegerType * getInt8Ty(LLVMContext &C)
INITIALIZE_PASS_BEGIN(NewGVNLegacyPass, "newgvn", "Global Value Numbering", false, false) INITIALIZE_PASS_END(NewGVNLegacyPass
void allocateOperands(RecyclerType &Recycler, BumpPtrAllocator &Allocator)
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
bool operator==(const Expression &Other) const