97 #include <unordered_map>
100 using namespace llvm;
101 using namespace PatternMatch;
102 using namespace llvm::GVNExpression;
103 using namespace llvm::VNCoercion;
104 #define DEBUG_TYPE "newgvn"
106 STATISTIC(NumGVNInstrDeleted,
"Number of instructions deleted");
107 STATISTIC(NumGVNBlocksDeleted,
"Number of blocks deleted");
108 STATISTIC(NumGVNOpsSimplified,
"Number of Expressions simplified");
109 STATISTIC(NumGVNPhisAllSame,
"Number of PHIs whos arguments are all the same");
111 "Maximum Number of iterations it took to converge GVN");
112 STATISTIC(NumGVNLeaderChanges,
"Number of leader changes");
113 STATISTIC(NumGVNSortedLeaderChanges,
"Number of sorted leader changes");
114 STATISTIC(NumGVNAvoidedSortedLeaderChanges,
115 "Number of avoided sorted leader changes");
116 STATISTIC(NumGVNDeadStores,
"Number of redundant/dead stores eliminated");
117 STATISTIC(NumGVNPHIOfOpsCreated,
"Number of PHI of ops created");
119 "Number of things eliminated using PHI of ops");
121 "Controls which instructions are value numbered")
136 namespace GVNExpression {
137 Expression::~Expression() =
default;
138 BasicExpression::~BasicExpression() =
default;
139 CallExpression::~CallExpression() =
default;
140 LoadExpression::~LoadExpression() =
default;
141 StoreExpression::~StoreExpression() =
default;
142 AggregateValueExpression::~AggregateValueExpression() =
default;
143 PHIExpression::~PHIExpression() =
default;
160 if (Root.lookup(Start) == 0)
165 unsigned ComponentID = ValueToComponent.lookup(V);
168 "Asking for a component for a value we never processed");
169 return Components[ComponentID];
176 unsigned int OurDFS = DFSNum;
178 if (
auto *InstOp = dyn_cast<Instruction>(
Op)) {
179 if (Root.lookup(
Op) == 0)
181 if (!InComponent.count(
Op))
182 Root[I] =
std::min(Root.lookup(I), Root.lookup(
Op));
189 if (Root.lookup(I) == OurDFS) {
190 unsigned ComponentID = Components.size();
191 Components.resize(Components.size() + 1);
192 auto &Component = Components.back();
194 DEBUG(
dbgs() <<
"Component root is " << *I <<
"\n");
195 InComponent.insert(I);
196 ValueToComponent[
I] = ComponentID;
198 while (!
Stack.empty() && Root.lookup(
Stack.back()) >= OurDFS) {
200 DEBUG(
dbgs() <<
"Component member is " << *Member <<
"\n");
201 Component.insert(Member);
202 InComponent.insert(Member);
203 ValueToComponent[
Member] = ComponentID;
211 unsigned int DFSNum = 1;
267 : ID(ID), RepLeader(Leader), DefiningExpr(E) {}
274 return empty() && memory_empty();
285 if (LeaderPair.second < NextLeader.second)
286 NextLeader = LeaderPair;
298 bool empty()
const {
return Members.empty(); }
299 unsigned size()
const {
return Members.size(); }
310 return MemoryMembers.begin();
313 return MemoryMembers.end();
316 return make_range(memory_begin(), memory_end());
325 assert(StoreCount != 0 &&
"Store count went negative");
341 if (std::tie(StoreCount, RepLeader, RepStoredValue, RepMemoryAccess) !=
342 std::tie(Other->StoreCount, Other->RepLeader, Other->RepStoredValue,
343 Other->RepMemoryAccess))
345 if (DefiningExpr != Other->DefiningExpr)
346 if (!DefiningExpr || !Other->DefiningExpr ||
347 *DefiningExpr != *Other->DefiningExpr)
350 std::set<Value *> AMembers(Members.begin(), Members.end());
351 std::set<Value *> BMembers(Members.begin(), Members.end());
352 return AMembers == BMembers;
358 Value *RepLeader =
nullptr;
361 std::pair<Value *, unsigned int> NextLeader = {
nullptr, ~0U};
363 Value *RepStoredValue =
nullptr;
374 MemoryMemberSet MemoryMembers;
386 return E.exactlyEquals(Other);
392 auto Val =
static_cast<uintptr_t
>(-1);
393 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
394 return reinterpret_cast<const Expression *
>(Val);
397 auto Val =
static_cast<uintptr_t
>(~1U);
398 Val <<= PointerLikeTypeTraits<const Expression *>::NumLowBitsAvailable;
399 return reinterpret_cast<const Expression *
>(Val);
408 if (RHS == getTombstoneKey() || RHS == getEmptyKey())
416 if (LHS == getTombstoneKey() || RHS == getTombstoneKey() ||
417 LHS == getEmptyKey() || RHS == getEmptyKey())
439 std::unique_ptr<PredicateInfo> PredInfo;
449 unsigned int NumFuncArgs;
461 std::vector<CongruenceClass *> CongruenceClasses;
462 unsigned NextCongruenceNum;
487 ExpressionToPhiOfOps;
523 enum MemoryPhiState { MPS_Invalid, MPS_TOP, MPS_Equivalent, MPS_Unique };
526 enum InstCycleState { ICS_Unknown, ICS_CycleFree, ICS_Cycle };
530 ExpressionClassMap ExpressionToClass;
581 : F(F), DT(DT), TLI(TLI), AA(AA), MSSA(MSSA), DL(DL),
592 bool &OriginalOpsConstant)
const;
605 createAggregateValueExpression(
Instruction *)
const;
611 CongruenceClasses.emplace_back(result);
616 auto *CC = createCongruenceClass(
nullptr,
nullptr);
617 CC->setMemoryLeader(MA);
621 auto *CC = getMemoryClass(MA);
622 if (CC->getMemoryLeader() != MA)
623 CC = createMemoryClass(MA);
630 ValueToClass[Member] = CClass;
633 void initializeCongruenceClasses(
Function &
F);
674 unsigned int getRank(
const Value *)
const;
675 bool shouldSwapOperands(
const Value *,
const Value *)
const;
680 Value *findConditionEquivalence(
Value *)
const;
691 bool eliminateInstructions(
Function &);
701 template <
typename Map,
typename KeyType,
typename Func>
702 void for_each_found(Map &,
const KeyType &, Func);
703 template <
typename Map,
typename KeyType>
704 void touchAndErase(Map &,
const KeyType &);
705 void markUsersTouched(
Value *);
711 void markPhiOfOpsChanged(
const Expression *E);
717 void iterateTouchedInstructions();
720 void cleanupTables();
721 std::pair<unsigned, unsigned> assignDFSNumbers(
BasicBlock *,
unsigned);
722 void updateProcessedCount(
const Value *V);
723 void verifyMemoryCongruency()
const;
724 void verifyIterationSettled(
Function &
F);
725 void verifyStoreExpressions()
const;
729 void deleteExpression(
const Expression *E)
const;
733 template <
class T,
class Range>
T *getMinDFSOfRange(
const Range &)
const;
734 unsigned InstrToDFSNum(
const Value *V)
const {
735 assert(isa<Instruction>(V) &&
"This should not be used for MemoryAccesses");
736 return InstrDFS.lookup(V);
740 return MemoryToDFSNum(MA);
742 Value *InstrFromDFSNum(
unsigned DFSNum) {
return DFSToInstr[DFSNum]; }
746 unsigned MemoryToDFSNum(
const Value *MA)
const {
747 assert(isa<MemoryAccess>(MA) &&
748 "This should not be used with instructions");
749 return isa<MemoryUseOrDef>(MA)
750 ? InstrToDFSNum(cast<MemoryUseOrDef>(MA)->getMemoryInst())
751 : InstrDFS.lookup(MA);
757 std::pair<int, int> StartingVNCounter;
761 template <
typename T>
763 if (!isa<LoadExpression>(RHS) && !isa<StoreExpression>(RHS))
765 return LHS.MemoryExpression::equals(RHS);
776 if (
const auto *S = dyn_cast<StoreExpression>(&Other))
777 if (getStoredValue() != S->getStoredValue())
786 auto *FromDTN = DT->getNode(From);
787 auto *ToDTN = DT->getNode(To);
788 return RPOOrdering.lookup(FromDTN) >= RPOOrdering.lookup(ToDTN);
799 auto *Result = MSSA->getMemoryAccess(I);
800 return Result ? Result : TempToMemory.lookup(I);
805 return MSSA->getMemoryAccess(BB);
810 if (
auto *I = dyn_cast<Instruction>(V)) {
814 Parent = TempToBlock.lookup(V);
815 assert(Parent &&
"Every fake instruction should have a block");
820 assert(MP &&
"Should have been an instruction or a MemoryPhi");
821 return MP->getBlock();
827 void NewGVN::deleteExpression(
const Expression *E)
const {
828 assert(isa<BasicExpression>(E));
829 auto *BE = cast<BasicExpression>(
E);
831 ExpressionAllocator.Deallocate(E);
834 bool &OriginalOpsConstant)
const {
836 auto *PN = cast<PHINode>(
I);
838 new (ExpressionAllocator)
PHIExpression(PN->getNumOperands(), PHIBlock);
853 for (
const Use &U : PN->operands())
856 [&](
const Use *U1,
const Use *U2) {
857 return PN->getIncomingBlock(*U1) < PN->getIncomingBlock(*U2);
864 if (!ReachableEdges.count({PN->getIncomingBlock(*U), PHIBlock}))
867 if (ValueToClass.lookup(*U) == TOPClass)
869 return lookupOperandLeader(*U) != PN;
873 auto *BB = PN->getIncomingBlock(*U);
874 HasBackedge = HasBackedge || isBackedge(BB, PHIBlock);
875 OriginalOpsConstant =
876 OriginalOpsConstant && isa<Constant>(*U);
877 return lookupOperandLeader(*U);
885 bool AllConstant =
true;
886 if (
auto *
GEP = dyn_cast<GetElementPtrInst>(I))
896 auto Operand = lookupOperandLeader(O);
897 AllConstant = AllConstant && isa<Constant>(Operand);
904 const Expression *NewGVN::createBinaryExpression(
unsigned Opcode,
Type *
T,
917 if (shouldSwapOperands(Arg1, Arg2))
924 if (
const Expression *SimplifiedE = checkSimplificationResults(E,
nullptr, V))
939 if (
auto *
C = dyn_cast<Constant>(V)) {
941 DEBUG(
dbgs() <<
"Simplified " << *I <<
" to "
942 <<
" constant " << *
C <<
"\n");
943 NumGVNOpsSimplified++;
944 assert(isa<BasicExpression>(E) &&
945 "We should always have had a basic expression here");
947 return createConstantExpression(
C);
948 }
else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
950 DEBUG(
dbgs() <<
"Simplified " << *I <<
" to "
951 <<
" variable " << *V <<
"\n");
953 return createVariableExpression(V);
962 if (!AllTempInstructions.count(I))
963 addAdditionalUsers(V, I);
967 DEBUG(
dbgs() <<
"Simplified " << *I <<
" to "
969 NumGVNOpsSimplified++;
979 bool AllConstant = setBasicExpressionInfo(I, E);
987 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1)))
988 E->swapOperands(0, 1);
999 if (
auto *CI = dyn_cast<CmpInst>(I)) {
1003 if (shouldSwapOperands(E->getOperand(0), E->getOperand(1))) {
1004 E->swapOperands(0, 1);
1007 E->
setOpcode((CI->getOpcode() << 8) | Predicate);
1010 "Wrong types on cmp instruction");
1015 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1017 }
else if (isa<SelectInst>(I)) {
1018 if (isa<Constant>(E->getOperand(0)) ||
1019 E->getOperand(0) == E->getOperand(1)) {
1023 E->getOperand(2), SQ);
1024 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1030 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1032 }
else if (
auto *BI = dyn_cast<BitCastInst>(I)) {
1035 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1037 }
else if (isa<GetElementPtrInst>(I)) {
1040 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1042 }
else if (AllConstant) {
1051 for (
Value *Arg : E->operands())
1055 if (
const Expression *SimplifiedE = checkSimplificationResults(E, I, V))
1062 NewGVN::createAggregateValueExpression(
Instruction *I)
const {
1063 if (
auto *II = dyn_cast<InsertValueInst>(I)) {
1064 auto *E =
new (ExpressionAllocator)
1066 setBasicExpressionInfo(I, E);
1067 E->allocateIntOperands(ExpressionAllocator);
1070 }
else if (
auto *EI = dyn_cast<ExtractValueInst>(I)) {
1071 auto *E =
new (ExpressionAllocator)
1073 setBasicExpressionInfo(EI, E);
1074 E->allocateIntOperands(ExpressionAllocator);
1084 return SingletonDeadExpression;
1094 if (
auto *C = dyn_cast<Constant>(V))
1095 return createConstantExpression(C);
1096 return createVariableExpression(V);
1116 setBasicExpressionInfo(CI, E);
1121 bool NewGVN::someEquivalentDominates(
const Instruction *Inst,
1123 auto *CC = ValueToClass.lookup(Inst);
1142 if (DT->dominates(cast<Instruction>(CC->
getLeader()), U))
1145 DT->dominates(cast<Instruction>(CC->
getNextLeader().first), U))
1149 DT->dominates(cast<Instruction>(Member), U);
1155 Value *NewGVN::lookupOperandLeader(
Value *V)
const {
1170 auto *CC = getMemoryClass(MA);
1172 "Every MemoryAccess should be mapped to a congruence class with a "
1173 "representative memory access");
1180 bool NewGVN::isMemoryAccessTOP(
const MemoryAccess *MA)
const {
1181 return getMemoryClass(MA) == TOPClass;
1188 new (ExpressionAllocator)
LoadExpression(1, LI, lookupMemoryLeader(MA));
1189 E->allocateOperands(ArgRecycler, ExpressionAllocator);
1190 E->setType(LoadType);
1194 E->op_push_back(PointerOp);
1207 auto *E =
new (ExpressionAllocator)
1225 auto *SI = cast<StoreInst>(
I);
1226 auto *StoreAccess = getMemoryAccess(SI);
1228 const MemoryAccess *StoreRHS = StoreAccess->getDefiningAccess();
1230 StoreRHS = MSSAWalker->getClobberingMemoryAccess(StoreAccess);
1232 if (StoreRHS != StoreAccess->getDefiningAccess())
1233 addMemoryUsers(StoreRHS, StoreAccess);
1234 StoreRHS = lookupMemoryLeader(StoreRHS);
1236 if (StoreRHS == StoreAccess)
1237 StoreRHS = MSSA->getLiveOnEntryDef();
1243 const auto *LastStore = createStoreExpression(SI, StoreRHS);
1244 const auto *LastCC = ExpressionToClass.lookup(LastStore);
1250 if (LastCC && LastCC->getStoredValue() == LastStore->getStoredValue())
1256 if (
auto *LI = dyn_cast<LoadInst>(LastStore->getStoredValue()))
1258 LastStore->getOperand(0)) &&
1259 (lookupMemoryLeader(getMemoryAccess(LI)->getDefiningAccess()) ==
1262 deleteExpression(LastStore);
1268 return createStoreExpression(SI, StoreAccess);
1274 NewGVN::performSymbolicLoadCoercion(
Type *LoadType,
Value *LoadPtr,
1278 if (
auto *DepSI = dyn_cast<StoreInst>(DepInst)) {
1282 if (LI->
isAtomic() > DepSI->isAtomic() ||
1283 LoadType == DepSI->getValueOperand()->getType())
1287 if (
auto *C = dyn_cast<Constant>(
1288 lookupOperandLeader(DepSI->getValueOperand()))) {
1289 DEBUG(
dbgs() <<
"Coercing load from store " << *DepSI <<
" to constant "
1291 return createConstantExpression(
1296 }
else if (
LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
1298 if (LI->
isAtomic() > DepLI->isAtomic())
1303 if (
auto *C = dyn_cast<Constant>(lookupOperandLeader(DepLI)))
1304 if (
auto *PossibleConstant =
1306 DEBUG(
dbgs() <<
"Coercing load from load " << *LI <<
" to constant "
1307 << *PossibleConstant <<
"\n");
1308 return createConstantExpression(PossibleConstant);
1312 }
else if (
MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
1315 if (
auto *PossibleConstant =
1317 DEBUG(
dbgs() <<
"Coercing load from meminst " << *DepMI
1318 <<
" to constant " << *PossibleConstant <<
"\n");
1319 return createConstantExpression(PossibleConstant);
1326 if (LoadPtr != lookupOperandLeader(DepInst) &&
1327 !AA->isMustAlias(LoadPtr, DepInst))
1338 else if (
auto *II = dyn_cast<IntrinsicInst>(DepInst)) {
1339 if (II->getIntrinsicID() == Intrinsic::lifetime_start)
1352 auto *LI = cast<LoadInst>(
I);
1361 if (isa<UndefValue>(LoadAddressLeader))
1365 MSSAWalker->getClobberingMemoryAccess(OriginalAccess);
1367 if (!MSSA->isLiveOnEntryDef(DefiningAccess)) {
1368 if (
auto *MD = dyn_cast<MemoryDef>(DefiningAccess)) {
1371 if (!ReachableBlocks.count(DefiningInst->
getParent()))
1377 if (
const auto *CoercionResult =
1378 performSymbolicLoadCoercion(LI->
getType(), LoadAddressLeader, LI,
1379 DefiningInst, DefiningAccess))
1380 return CoercionResult;
1385 LI, DefiningAccess);
1390 NewGVN::performSymbolicPredicateInfoEvaluation(
Instruction *I)
const {
1391 auto *PI = PredInfo->getPredicateInfoFor(I);
1395 DEBUG(
dbgs() <<
"Found predicate info from instruction !\n");
1402 auto *Cond = PWC->Condition;
1406 if (CopyOf == Cond) {
1409 if (isa<PredicateAssume>(PI))
1411 if (
auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1412 if (PBranch->TrueEdge)
1416 if (
auto *PSwitch = dyn_cast<PredicateSwitch>(PI))
1417 return createConstantExpression(cast<Constant>(PSwitch->CaseValue));
1434 if (CopyOf != Cmp->getOperand(0) && CopyOf != Cmp->getOperand(1)) {
1435 DEBUG(
dbgs() <<
"Copy is not of any condition operands!\n");
1438 Value *FirstOp = lookupOperandLeader(Cmp->getOperand(0));
1439 Value *SecondOp = lookupOperandLeader(Cmp->getOperand(1));
1440 bool SwappedOps =
false;
1442 if (shouldSwapOperands(FirstOp, SecondOp)) {
1447 SwappedOps ? Cmp->getSwappedPredicate() : Cmp->getPredicate();
1449 if (isa<PredicateAssume>(PI)) {
1453 addPredicateUsers(PI, I);
1454 addAdditionalUsers(Cmp->getOperand(0),
I);
1455 return createVariableOrConstant(FirstOp);
1458 if (
const auto *PBranch = dyn_cast<PredicateBranch>(PI)) {
1466 addPredicateUsers(PI, I);
1467 addAdditionalUsers(Cmp->getOperand(0),
I);
1468 return createVariableOrConstant(FirstOp);
1473 isa<ConstantFP>(FirstOp) && !cast<ConstantFP>(FirstOp)->isZero()) {
1474 addPredicateUsers(PI, I);
1475 addAdditionalUsers(Cmp->getOperand(0),
I);
1476 return createConstantExpression(cast<Constant>(FirstOp));
1484 auto *CI = cast<CallInst>(
I);
1485 if (
auto *II = dyn_cast<IntrinsicInst>(I)) {
1487 if (
auto *ReturnedValue = II->getReturnedArgOperand()) {
1488 if (II->getIntrinsicID() == Intrinsic::ssa_copy)
1489 if (
const auto *Result = performSymbolicPredicateInfoEvaluation(I))
1491 return createVariableOrConstant(ReturnedValue);
1494 if (AA->doesNotAccessMemory(CI)) {
1495 return createCallExpression(CI, TOPClass->getMemoryLeader());
1496 }
else if (AA->onlyReadsMemory(CI)) {
1497 MemoryAccess *DefiningAccess = MSSAWalker->getClobberingMemoryAccess(CI);
1498 return createCallExpression(CI, DefiningAccess);
1506 auto *Result = MemoryAccessToClass.lookup(MA);
1507 assert(Result &&
"Should have found memory class");
1516 "Every MemoryAccess should be getting mapped to a non-null class");
1518 DEBUG(
dbgs() <<
" equivalent to congruence class ");
1519 DEBUG(
dbgs() << NewClass->
getID() <<
" with current MemoryAccess leader ");
1522 auto LookupResult = MemoryAccessToClass.find(From);
1523 bool Changed =
false;
1525 if (LookupResult != MemoryAccessToClass.end()) {
1526 auto *OldClass = LookupResult->second;
1527 if (OldClass != NewClass) {
1529 if (
auto *MP = dyn_cast<MemoryPhi>(From)) {
1530 OldClass->memory_erase(MP);
1533 if (OldClass->getMemoryLeader() == From) {
1534 if (OldClass->definesNoMemory()) {
1535 OldClass->setMemoryLeader(
nullptr);
1537 OldClass->setMemoryLeader(getNextMemoryLeader(OldClass));
1538 DEBUG(
dbgs() <<
"Memory class leader change for class "
1539 << OldClass->getID() <<
" to "
1540 << *OldClass->getMemoryLeader()
1541 <<
" due to removal of a memory member " << *From
1543 markMemoryLeaderChangeTouched(OldClass);
1548 LookupResult->second = NewClass;
1560 bool NewGVN::isCycleFree(
const Instruction *I)
const {
1566 auto ICS = InstCycleState.lookup(I);
1567 if (ICS == ICS_Unknown) {
1569 auto &SCC = SCCFinder.getComponentFor(I);
1571 if (SCC.size() == 1)
1572 InstCycleState.insert({I, ICS_CycleFree});
1576 ICS = AllPhis ? ICS_CycleFree : ICS_Cycle;
1577 for (
auto *Member : SCC)
1578 if (
auto *MemberPhi = dyn_cast<PHINode>(Member))
1579 InstCycleState.insert({MemberPhi, ICS});
1582 if (ICS == ICS_Cycle)
1590 bool HasBackedge =
false;
1595 bool AllConstant =
true;
1597 cast<PHIExpression>(createPHIExpression(I, HasBackedge, AllConstant));
1601 bool HasUndef =
false;
1603 if (isa<UndefValue>(Arg)) {
1610 if (Filtered.begin() == Filtered.end()) {
1615 <<
" has no non-undef arguments, valuing it as undef\n");
1619 DEBUG(
dbgs() <<
"No arguments of PHI node " << *I <<
" are live\n");
1620 deleteExpression(E);
1621 return createDeadExpression();
1623 unsigned NumOps = 0;
1624 Value *AllSameValue = *(Filtered.begin());
1629 return Arg == AllSameValue;
1647 if (!AllConstant && HasBackedge && NumOps > 0 &&
1648 !isa<UndefValue>(AllSameValue) && !isCycleFree(I))
1652 if (
auto *AllSameInst = dyn_cast<Instruction>(AllSameValue))
1653 if (!someEquivalentDominates(AllSameInst, I))
1659 if (isa<Instruction>(AllSameValue) &&
1660 InstrToDFSNum(AllSameValue) > InstrToDFSNum(I))
1662 NumGVNPhisAllSame++;
1663 DEBUG(
dbgs() <<
"Simplified PHI node " << *I <<
" to " << *AllSameValue
1665 deleteExpression(E);
1666 return createVariableOrConstant(AllSameValue);
1672 NewGVN::performSymbolicAggrValueEvaluation(
Instruction *I)
const {
1673 if (
auto *EI = dyn_cast<ExtractValueInst>(I)) {
1675 if (II && EI->getNumIndices() == 1 && *EI->idx_begin() == 0) {
1676 unsigned Opcode = 0;
1680 switch (II->getIntrinsicID()) {
1681 case Intrinsic::sadd_with_overflow:
1682 case Intrinsic::uadd_with_overflow:
1685 case Intrinsic::ssub_with_overflow:
1686 case Intrinsic::usub_with_overflow:
1687 Opcode = Instruction::Sub;
1689 case Intrinsic::smul_with_overflow:
1690 case Intrinsic::umul_with_overflow:
1691 Opcode = Instruction::Mul;
1700 assert(II->getNumArgOperands() == 2 &&
1701 "Expect two args for recognised intrinsics.");
1702 return createBinaryExpression(
1703 Opcode, EI->getType(), II->getArgOperand(0), II->getArgOperand(1));
1708 return createAggregateValueExpression(I);
1714 auto Op0 = lookupOperandLeader(CI->
getOperand(0));
1715 auto Op1 = lookupOperandLeader(CI->
getOperand(1));
1716 auto OurPredicate = CI->getPredicate();
1717 if (shouldSwapOperands(Op0, Op1)) {
1719 OurPredicate = CI->getSwappedPredicate();
1726 auto *CmpPI = PredInfo->getPredicateInfoFor(I);
1727 if (dyn_cast_or_null<PredicateAssume>(CmpPI))
1732 if (CI->isTrueWhenEqual())
1734 else if (CI->isFalseWhenEqual())
1764 auto *PI = PredInfo->getPredicateInfoFor(
Op);
1765 if (
const auto *PBranch = dyn_cast_or_null<PredicateBranch>(PI)) {
1766 if (PI == LastPredInfo)
1776 auto *BranchOp0 = lookupOperandLeader(BranchCond->getOperand(0));
1777 auto *BranchOp1 = lookupOperandLeader(BranchCond->getOperand(1));
1779 if (shouldSwapOperands(BranchOp0, BranchOp1)) {
1781 BranchPredicate = BranchCond->getSwappedPredicate();
1783 if (BranchOp0 == Op0 && BranchOp1 == Op1) {
1784 if (PBranch->TrueEdge) {
1789 addPredicateUsers(PI, I);
1790 return createConstantExpression(
1796 addPredicateUsers(PI, I);
1797 return createConstantExpression(
1804 if (BranchPredicate == OurPredicate) {
1805 addPredicateUsers(PI, I);
1807 return createConstantExpression(
1809 }
else if (BranchPredicate ==
1811 addPredicateUsers(PI, I);
1813 return createConstantExpression(
1821 return createExpression(I);
1829 return isa<Constant>(V) || isa<Argument>(V);
1834 NewGVN::performSymbolicEvaluation(
Value *V,
1837 if (
auto *C = dyn_cast<Constant>(V))
1838 E = createConstantExpression(C);
1839 else if (isa<Argument>(V) || isa<GlobalVariable>(V)) {
1840 E = createVariableExpression(V);
1845 auto *I = cast<Instruction>(V);
1847 case Instruction::ExtractValue:
1848 case Instruction::InsertValue:
1849 E = performSymbolicAggrValueEvaluation(I);
1851 case Instruction::PHI:
1852 E = performSymbolicPHIEvaluation(I);
1855 E = performSymbolicCallEvaluation(I);
1858 E = performSymbolicStoreEvaluation(I);
1861 E = performSymbolicLoadEvaluation(I);
1863 case Instruction::BitCast: {
1864 E = createExpression(I);
1866 case Instruction::ICmp:
1867 case Instruction::FCmp: {
1868 E = performSymbolicCmpEvaluation(I);
1871 case Instruction::FAdd:
1872 case Instruction::Sub:
1873 case Instruction::FSub:
1874 case Instruction::Mul:
1875 case Instruction::FMul:
1876 case Instruction::UDiv:
1877 case Instruction::SDiv:
1878 case Instruction::FDiv:
1879 case Instruction::URem:
1880 case Instruction::SRem:
1881 case Instruction::FRem:
1882 case Instruction::Shl:
1883 case Instruction::LShr:
1884 case Instruction::AShr:
1885 case Instruction::And:
1886 case Instruction::Or:
1887 case Instruction::Xor:
1888 case Instruction::Trunc:
1889 case Instruction::ZExt:
1890 case Instruction::SExt:
1891 case Instruction::FPToUI:
1892 case Instruction::FPToSI:
1893 case Instruction::UIToFP:
1894 case Instruction::SIToFP:
1895 case Instruction::FPTrunc:
1896 case Instruction::FPExt:
1897 case Instruction::PtrToInt:
1898 case Instruction::IntToPtr:
1900 case Instruction::ExtractElement:
1901 case Instruction::InsertElement:
1902 case Instruction::ShuffleVector:
1903 case Instruction::GetElementPtr:
1904 E = createExpression(I);
1915 template <
typename Map,
typename KeyType,
typename Func>
1916 void NewGVN::for_each_found(Map &M,
const KeyType &Key, Func
F) {
1917 const auto Result = M.find_as(Key);
1918 if (Result != M.end())
1919 for (
typename Map::mapped_type::value_type Mapped : Result->second)
1925 template <
typename Map,
typename KeyType>
1926 void NewGVN::touchAndErase(Map &M,
const KeyType &Key) {
1927 const auto Result = M.find_as(Key);
1928 if (Result != M.end()) {
1929 for (
const typename Map::mapped_type::value_type Mapped : Result->second)
1930 TouchedInstructions.set(InstrToDFSNum(Mapped));
1936 if (isa<Instruction>(To))
1937 AdditionalUsers[To].insert(User);
1940 void NewGVN::markUsersTouched(
Value *V) {
1942 for (
auto *User : V->
users()) {
1943 assert(isa<Instruction>(User) &&
"Use of value not within an instruction?");
1944 TouchedInstructions.set(InstrToDFSNum(User));
1946 touchAndErase(AdditionalUsers, V);
1950 DEBUG(
dbgs() <<
"Adding memory user " << *U <<
" to " << *To <<
"\n");
1951 MemoryToUsers[To].insert(U);
1954 void NewGVN::markMemoryDefTouched(
const MemoryAccess *MA) {
1955 TouchedInstructions.set(MemoryToDFSNum(MA));
1958 void NewGVN::markMemoryUsersTouched(
const MemoryAccess *MA) {
1959 if (isa<MemoryUse>(MA))
1961 for (
auto U : MA->
users())
1962 TouchedInstructions.set(MemoryToDFSNum(U));
1963 touchAndErase(MemoryToUsers, MA);
1969 if (AllTempInstructions.count(I))
1972 if (
auto *PBranch = dyn_cast<PredicateBranch>(PB))
1973 PredicateToUsers[PBranch->Condition].insert(I);
1974 else if (
auto *PAssume = dyn_cast<PredicateBranch>(PB))
1975 PredicateToUsers[PAssume->Condition].insert(I);
1979 void NewGVN::markPredicateUsersTouched(
Instruction *I) {
1980 touchAndErase(PredicateToUsers, I);
1985 for (
auto M : CC->
memory())
1986 markMemoryDefTouched(M);
1992 for (
auto M : *CC) {
1993 if (
auto *I = dyn_cast<Instruction>(M))
1994 TouchedInstructions.set(InstrToDFSNum(I));
1995 LeaderChanges.insert(M);
2001 template <
class T,
class Range>
2002 T *NewGVN::getMinDFSOfRange(
const Range &R)
const {
2003 std::pair<T *, unsigned> MinDFS = {
nullptr, ~0U};
2004 for (
const auto X : R) {
2005 auto DFSNum = InstrToDFSNum(
X);
2006 if (DFSNum < MinDFS.second)
2007 MinDFS = {
X, DFSNum};
2009 return MinDFS.first;
2021 if (
auto *NL = dyn_cast_or_null<StoreInst>(CC->
getNextLeader().first))
2022 return getMemoryAccess(NL);
2025 *CC, [&](
const Value *V) {
return isa<StoreInst>(V); }));
2026 return getMemoryAccess(cast<StoreInst>(V));
2034 return getMinDFSOfRange<const MemoryPhi>(CC->
memory());
2045 if (CC->
size() == 1 || CC == TOPClass) {
2046 return *(CC->
begin());
2048 ++NumGVNAvoidedSortedLeaderChanges;
2051 ++NumGVNSortedLeaderChanges;
2055 return getMinDFSOfRange<Value>(*CC);
2068 void NewGVN::moveMemoryToNewCongruenceClass(
Instruction *I,
2077 MemoryAccessToClass.lookup(InstMA)) &&
2078 "Representative MemoryAccess mismatch");
2086 DEBUG(
dbgs() <<
"Memory class leader change for class " << NewClass->
getID()
2087 <<
" due to new memory instruction becoming leader\n");
2088 markMemoryLeaderChangeTouched(NewClass);
2090 setMemoryClass(InstMA, NewClass);
2095 DEBUG(
dbgs() <<
"Memory class leader change for class "
2096 << OldClass->
getID() <<
" to "
2098 <<
" due to removal of old leader " << *InstMA <<
"\n");
2099 markMemoryLeaderChangeTouched(OldClass);
2119 if (
auto *SI = dyn_cast<StoreInst>(I)) {
2131 if (
auto *SE = dyn_cast<StoreExpression>(E)) {
2133 markValueLeaderChangeTouched(NewClass);
2135 DEBUG(
dbgs() <<
"Changing leader of congruence class "
2137 <<
" to " << *SI <<
" because store joined class\n");
2150 auto *InstMA = dyn_cast_or_null<MemoryDef>(getMemoryAccess(I));
2152 moveMemoryToNewCongruenceClass(I, InstMA, OldClass, NewClass);
2153 ValueToClass[
I] = NewClass;
2155 if (OldClass->
empty() && OldClass != TOPClass) {
2158 <<
" from table\n");
2161 auto Iter = ExpressionToClass.find_as(
2163 if (Iter != ExpressionToClass.end())
2164 ExpressionToClass.erase(Iter);
2165 #ifdef EXPENSIVE_CHECKS
2167 (*OldClass->
getDefiningExpr() != *E || ExpressionToClass.lookup(E)) &&
2168 "We erased the expression we just inserted, which should not happen");
2175 DEBUG(
dbgs() <<
"Value class leader change for class " << OldClass->
getID()
2177 ++NumGVNLeaderChanges;
2186 OldClass->
setLeader(getNextValueLeader(OldClass));
2188 markValueLeaderChangeTouched(OldClass);
2194 void NewGVN::markPhiOfOpsChanged(
const Expression *E) {
2204 assert(IClass &&
"Should have found a IClass");
2209 if (
const auto *VE = dyn_cast<VariableExpression>(E)) {
2210 EClass = ValueToClass.lookup(VE->getVariableValue());
2211 }
else if (isa<DeadExpression>(E)) {
2215 auto lookupResult = ExpressionToClass.
insert({
E,
nullptr});
2218 if (lookupResult.second) {
2220 auto place = lookupResult.first;
2221 place->second = NewClass;
2224 if (
const auto *CE = dyn_cast<ConstantExpression>(E)) {
2226 }
else if (
const auto *SE = dyn_cast<StoreExpression>(E)) {
2235 assert(!isa<VariableExpression>(E) &&
2236 "VariableExpression should have been handled already");
2239 DEBUG(
dbgs() <<
"Created new congruence class for " << *I
2240 <<
" using expression " << *E <<
" at " << NewClass->
getID()
2241 <<
" and leader " << *(NewClass->
getLeader()));
2246 EClass = lookupResult.first->second;
2247 if (isa<ConstantExpression>(E))
2248 assert((isa<Constant>(EClass->getLeader()) ||
2249 (EClass->getStoredValue() &&
2250 isa<Constant>(EClass->getStoredValue()))) &&
2251 "Any class with a constant expression should have a "
2254 assert(EClass &&
"Somehow don't have an eclass");
2256 assert(!EClass->isDead() &&
"We accidentally looked up a dead class");
2259 bool ClassChanged = IClass != EClass;
2260 bool LeaderChanged = LeaderChanges.
erase(I);
2261 if (ClassChanged || LeaderChanged) {
2262 DEBUG(
dbgs() <<
"New class " << EClass->getID() <<
" for expression " << *E
2265 moveValueToNewCongruenceClass(I, E, IClass, EClass);
2266 markPhiOfOpsChanged(E);
2269 markUsersTouched(I);
2271 markMemoryUsersTouched(MA);
2272 if (
auto *CI = dyn_cast<CmpInst>(I))
2273 markPredicateUsersTouched(CI);
2279 if (ClassChanged && isa<StoreInst>(I)) {
2280 auto *OldE = ValueToExpression.lookup(I);
2283 if (OldE && isa<StoreExpression>(OldE) && *E != *OldE) {
2287 if (Iter != ExpressionToClass.end())
2288 ExpressionToClass.erase(Iter);
2291 ValueToExpression[
I] =
E;
2298 if (ReachableEdges.insert({From, To}).
second) {
2300 if (ReachableBlocks.insert(To).second) {
2302 const auto &InstRange = BlockInstRange.lookup(To);
2303 TouchedInstructions.set(InstRange.first, InstRange.second);
2306 <<
" was reachable, but new edge {" <<
getBlockName(From)
2314 TouchedInstructions.set(InstrToDFSNum(MemPhi));
2316 auto BI = To->
begin();
2317 while (isa<PHINode>(BI)) {
2318 TouchedInstructions.set(InstrToDFSNum(&*BI));
2321 for_each_found(PHIOfOpsPHIs, To, [&](
const PHINode *I) {
2322 TouchedInstructions.set(InstrToDFSNum(I));
2330 Value *NewGVN::findConditionEquivalence(
Value *Cond)
const {
2331 auto Result = lookupOperandLeader(Cond);
2332 return isa<Constant>(Result) ? Result :
nullptr;
2339 if ((BR = dyn_cast<BranchInst>(TI)) && BR->
isConditional()) {
2341 Value *CondEvaluated = findConditionEquivalence(Cond);
2342 if (!CondEvaluated) {
2343 if (
auto *I = dyn_cast<Instruction>(Cond)) {
2345 if (
const auto *CE = dyn_cast<ConstantExpression>(E)) {
2346 CondEvaluated =
CE->getConstantValue();
2348 }
else if (isa<ConstantInt>(Cond)) {
2349 CondEvaluated = Cond;
2355 if (CondEvaluated && (CI = dyn_cast<ConstantInt>(CondEvaluated))) {
2357 DEBUG(
dbgs() <<
"Condition for Terminator " << *TI
2358 <<
" evaluated to true\n");
2359 updateReachableEdge(B, TrueSucc);
2360 }
else if (CI->
isZero()) {
2361 DEBUG(
dbgs() <<
"Condition for Terminator " << *TI
2362 <<
" evaluated to false\n");
2363 updateReachableEdge(B, FalseSucc);
2366 updateReachableEdge(B, TrueSucc);
2367 updateReachableEdge(B, FalseSucc);
2369 }
else if (
auto *SI = dyn_cast<SwitchInst>(TI)) {
2376 Value *SwitchCond = SI->getCondition();
2377 Value *CondEvaluated = findConditionEquivalence(SwitchCond);
2379 if (CondEvaluated && isa<ConstantInt>(CondEvaluated)) {
2380 auto *CondVal = cast<ConstantInt>(CondEvaluated);
2382 auto Case = *SI->findCaseValue(CondVal);
2383 if (Case.getCaseSuccessor() == SI->getDefaultDest()) {
2387 updateReachableEdge(B, SI->getDefaultDest());
2391 BasicBlock *TargetBlock = Case.getCaseSuccessor();
2392 updateReachableEdge(B, TargetBlock);
2394 for (
unsigned i = 0, e = SI->getNumSuccessors(); i != e; ++i) {
2395 BasicBlock *TargetBlock = SI->getSuccessor(i);
2396 ++SwitchEdges[TargetBlock];
2397 updateReachableEdge(B, TargetBlock);
2405 updateReachableEdge(B, TargetBlock);
2411 auto *MA = getMemoryAccess(TI);
2412 if (MA && !isa<MemoryUse>(MA)) {
2413 auto *CC = ensureLeaderOfMemoryClass(MA);
2414 if (setMemoryClass(MA, CC))
2415 markMemoryUsersTouched(MA);
2422 InstrDFS[
Op] = InstrToDFSNum(ExistingValue);
2423 AllTempInstructions.insert(Op);
2424 PHIOfOpsPHIs[BB].push_back(Op);
2425 TempToBlock[
Op] = BB;
2426 RealToTemp[ExistingValue] =
Op;
2430 return isa<BinaryOperator>(
I) || isa<SelectInst>(I) || isa<CmpInst>(
I) ||
2442 if (!Visited.
insert(I).second)
2448 if (!isCycleFree(I))
2451 unsigned IDFSNum = InstrToDFSNum(I);
2456 auto *MemAccess = getMemoryAccess(I);
2460 if (MemAccess && !isa<MemoryPhi>(MemAccess->getDefiningAccess()) &&
2461 MemAccess->getDefiningAccess()->getBlock() == I->
getParent())
2474 if (isa<Instruction>(Op) && PHINodeUses.count(cast<Instruction>(Op)))
2476 if (!isa<PHINode>(Op))
2478 auto *OpPHI = cast<PHINode>(
Op);
2480 if (OpPHI->getNumOperands() == 1)
2482 if (!DebugCounter::shouldExecute(PHIOfOpsCounter))
2485 auto *PHIBlock = getBlockForValue(OpPHI);
2486 for (
auto PredBB : OpPHI->blocks()) {
2487 Value *FoundVal =
nullptr;
2490 if (ReachableEdges.count({PredBB, PHIBlock})) {
2495 TempToMemory.insert({ValueOp, MemAccess});
2497 for (
auto &Op : ValueOp->
operands()) {
2501 addAdditionalUsers(Op, I);
2504 AllTempInstructions.insert(ValueOp);
2508 InstrDFS.insert({ValueOp, IDFSNum});
2509 const Expression *E = performSymbolicEvaluation(ValueOp, Visited);
2510 InstrDFS.erase(ValueOp);
2511 AllTempInstructions.erase(ValueOp);
2514 TempToMemory.erase(ValueOp);
2517 FoundVal = findPhiOfOpsLeader(E, PredBB);
2519 ExpressionToPhiOfOps[
E].insert(I);
2522 if (
auto *SI = dyn_cast<StoreInst>(FoundVal))
2525 DEBUG(
dbgs() <<
"Skipping phi of ops operand for incoming block "
2527 <<
" because the block is unreachable\n");
2528 FoundVal = UndefValue::get(I->
getType());
2532 DEBUG(
dbgs() <<
"Found phi of ops operand " << *FoundVal <<
" in "
2535 auto *ValuePHI = RealToTemp.lookup(I);
2536 bool NewPHI =
false;
2538 ValuePHI = PHINode::Create(I->
getType(), OpPHI->getNumOperands());
2539 addPhiOfOps(ValuePHI, PHIBlock, I);
2541 NumGVNPHIOfOpsCreated++;
2544 for (
auto PHIOp : Ops)
2545 ValuePHI->addIncoming(PHIOp.first, PHIOp.second);
2548 for (
auto PHIOp : Ops) {
2549 ValuePHI->setIncomingValue(i, PHIOp.first);
2550 ValuePHI->setIncomingBlock(i, PHIOp.second);
2555 DEBUG(
dbgs() <<
"Created phi of ops " << *ValuePHI <<
" for " << *I
2557 return performSymbolicEvaluation(ValuePHI, Visited);
2565 void NewGVN::initializeCongruenceClasses(
Function &F) {
2566 NextCongruenceNum = 0;
2576 TOPClass = createCongruenceClass(
nullptr,
nullptr);
2577 TOPClass->setMemoryLeader(MSSA->getLiveOnEntryDef());
2579 MemoryAccessToClass[MSSA->getLiveOnEntryDef()] =
2580 createMemoryClass(MSSA->getLiveOnEntryDef());
2582 for (
auto DTN :
nodes(DT)) {
2588 auto *MemoryBlockDefs = MSSA->getBlockDefs(BB);
2589 if (MemoryBlockDefs)
2590 for (
const auto &
Def : *MemoryBlockDefs) {
2591 MemoryAccessToClass[&
Def] = TOPClass;
2596 TOPClass->memory_insert(MP);
2597 MemoryPhiState.insert({MP, MPS_TOP});
2600 if (MD && isa<StoreInst>(MD->getMemoryInst()))
2601 TOPClass->incStoreCount();
2603 for (
auto &I : *BB) {
2605 if (isa<PHINode>(&I))
2606 for (
auto *U : I.
users())
2607 if (
auto *UInst = dyn_cast<Instruction>(U))
2609 PHINodeUses.insert(UInst);
2614 TOPClass->insert(&I);
2615 ValueToClass[&
I] = TOPClass;
2620 for (
auto &FA : F.
args())
2621 createSingletonCongruenceClass(&FA);
2624 void NewGVN::cleanupTables() {
2625 for (
unsigned i = 0, e = CongruenceClasses.size(); i != e; ++i) {
2626 DEBUG(
dbgs() <<
"Congruence class " << CongruenceClasses[i]->
getID()
2627 <<
" has " << CongruenceClasses[i]->size() <<
" members\n");
2630 delete CongruenceClasses[i];
2631 CongruenceClasses[i] =
nullptr;
2636 AllTempInstructions.end());
2637 AllTempInstructions.
clear();
2641 for (
auto *I : TempInst) {
2645 while (!TempInst.empty()) {
2646 auto *I = TempInst.back();
2647 TempInst.pop_back();
2651 ValueToClass.clear();
2652 ArgRecycler.clear(ExpressionAllocator);
2653 ExpressionAllocator.Reset();
2654 CongruenceClasses.clear();
2655 ExpressionToClass.clear();
2656 ValueToExpression.clear();
2658 AdditionalUsers.clear();
2659 ExpressionToPhiOfOps.clear();
2660 TempToBlock.clear();
2661 TempToMemory.clear();
2662 PHIOfOpsPHIs.clear();
2663 ReachableBlocks.clear();
2664 ReachableEdges.clear();
2666 ProcessedCount.clear();
2669 InstructionsToErase.clear();
2671 BlockInstRange.clear();
2672 TouchedInstructions.clear();
2673 MemoryAccessToClass.clear();
2674 PredicateToUsers.clear();
2675 MemoryToUsers.clear();
2680 std::pair<unsigned, unsigned> NewGVN::assignDFSNumbers(
BasicBlock *B,
2682 unsigned End = Start;
2684 InstrDFS[MemPhi] = End++;
2685 DFSToInstr.emplace_back(MemPhi);
2689 for (
auto &I : *B) {
2695 DEBUG(
dbgs() <<
"Skipping trivially dead instruction " << I <<
"\n");
2696 markInstructionForDeletion(&I);
2699 InstrDFS[&
I] = End++;
2700 DFSToInstr.emplace_back(&I);
2706 return std::make_pair(Start, End);
2709 void NewGVN::updateProcessedCount(
const Value *V) {
2711 if (ProcessedCount.count(V) == 0) {
2712 ProcessedCount.insert({V, 1});
2714 ++ProcessedCount[V];
2715 assert(ProcessedCount[V] < 100 &&
2716 "Seem to have processed the same Value a lot");
2721 void NewGVN::valueNumberMemoryPhi(
MemoryPhi *MP) {
2728 return cast<MemoryAccess>(U) != MP &&
2729 !isMemoryAccessTOP(cast<MemoryAccess>(U)) &&
2735 if (Filtered.begin() == Filtered.end()) {
2736 if (setMemoryClass(MP, TOPClass))
2737 markMemoryUsersTouched(MP);
2743 auto LookupFunc = [&](
const Use &U) {
2744 return lookupMemoryLeader(cast<MemoryAccess>(U));
2746 auto MappedBegin =
map_iterator(Filtered.begin(), LookupFunc);
2747 auto MappedEnd =
map_iterator(Filtered.end(), LookupFunc);
2751 const auto *AllSameValue = *MappedBegin;
2754 MappedBegin, MappedEnd,
2755 [&AllSameValue](
const MemoryAccess *V) {
return V == AllSameValue; });
2758 DEBUG(
dbgs() <<
"Memory Phi value numbered to " << *AllSameValue <<
"\n");
2760 DEBUG(
dbgs() <<
"Memory Phi value numbered to itself\n");
2767 AllEqual ? getMemoryClass(AllSameValue) : ensureLeaderOfMemoryClass(MP);
2768 auto OldState = MemoryPhiState.lookup(MP);
2769 assert(OldState != MPS_Invalid &&
"Invalid memory phi state");
2770 auto NewState = AllEqual ? MPS_Equivalent : MPS_Unique;
2771 MemoryPhiState[MP] = NewState;
2772 if (setMemoryClass(MP, CC) || OldState != NewState)
2773 markMemoryUsersTouched(MP);
2778 void NewGVN::valueNumberInstruction(
Instruction *I) {
2779 DEBUG(
dbgs() <<
"Processing instruction " << *I <<
"\n");
2783 if (DebugCounter::shouldExecute(VNCounter)) {
2784 Symbolized = performSymbolicEvaluation(I, Visited);
2786 if (Symbolized && !isa<ConstantExpression>(Symbolized) &&
2787 !isa<VariableExpression>(Symbolized) && PHINodeUses.count(I)) {
2788 auto *PHIE = makePossiblePhiOfOps(I, Visited);
2799 if (Symbolized ==
nullptr)
2800 Symbolized = createUnknownExpression(I);
2801 performCongruenceFinding(I, Symbolized);
2807 auto *Symbolized = createUnknownExpression(I);
2808 performCongruenceFinding(I, Symbolized);
2810 processOutgoingEdges(dyn_cast<TerminatorInst>(I), I->
getParent());
2816 bool NewGVN::singleReachablePHIPath(
2819 if (First == Second)
2821 if (MSSA->isLiveOnEntryDef(First))
2829 if (Visited.
count(First))
2833 const auto *EndDef = First;
2835 if (ChainDef == Second)
2837 if (MSSA->isLiveOnEntryDef(ChainDef))
2841 auto *MP = cast<MemoryPhi>(EndDef);
2842 auto ReachableOperandPred = [&](
const Use &U) {
2845 auto FilteredPhiArgs =
2848 std::copy(FilteredPhiArgs.begin(), FilteredPhiArgs.end(),
2849 std::back_inserter(OperandList));
2850 bool Okay = OperandList.
size() == 1;
2853 std::equal(OperandList.begin(), OperandList.end(), OperandList.begin());
2855 return singleReachablePHIPath(Visited, cast<MemoryAccess>(OperandList[0]),
2864 void NewGVN::verifyMemoryCongruency()
const {
2867 for (
const auto *CC : CongruenceClasses) {
2868 if (CC == TOPClass || CC->
isDead())
2872 "Any class with a store as a leader should have a "
2873 "representative stored value");
2875 "Any congruence class with a store should have a "
2876 "representative access");
2881 "Representative MemoryAccess does not appear to be reverse "
2883 for (
auto M : CC->
memory())
2884 assert(MemoryAccessToClass.lookup(M) == CC &&
2885 "Memory member does not appear to be reverse mapped properly");
2893 auto ReachableAccessPred =
2894 [&](
const std::pair<const MemoryAccess *, CongruenceClass *> Pair) {
2895 bool Result = ReachableBlocks.count(Pair.first->getBlock());
2896 if (!Result || MSSA->isLiveOnEntryDef(Pair.first) ||
2897 MemoryToDFSNum(Pair.first) == 0)
2899 if (
auto *MemDef = dyn_cast<MemoryDef>(Pair.first))
2904 if (
auto *MemPHI = dyn_cast<MemoryPhi>(Pair.first)) {
2905 for (
auto &U : MemPHI->incoming_values()) {
2906 if (
Instruction *I = dyn_cast<Instruction>(U.get())) {
2918 for (
auto KV : Filtered) {
2919 if (
auto *FirstMUD = dyn_cast<MemoryUseOrDef>(KV.first)) {
2921 if (FirstMUD && SecondMUD) {
2923 assert((singleReachablePHIPath(VisitedMAS, FirstMUD, SecondMUD) ||
2924 ValueToClass.lookup(FirstMUD->getMemoryInst()) ==
2925 ValueToClass.lookup(SecondMUD->getMemoryInst())) &&
2926 "The instructions for these memory operations should have "
2927 "been in the same congruence class or reachable through"
2928 "a single argument phi");
2930 }
else if (
auto *FirstMP = dyn_cast<MemoryPhi>(KV.first)) {
2933 auto ReachableOperandPred = [&](
const Use &U) {
2934 return ReachableEdges.count(
2935 {FirstMP->getIncomingBlock(U), FirstMP->getBlock()}) &&
2940 auto FilteredPhiArgs =
2944 std::back_inserter(PhiOpClasses), [&](
const Use &U) {
2945 const MemoryDef *MD = cast<MemoryDef>(U);
2949 PhiOpClasses.begin()) &&
2950 "All MemoryPhi arguments should be in the same class");
2959 void NewGVN::verifyIterationSettled(
Function &F) {
2961 DEBUG(
dbgs() <<
"Beginning iteration verification\n");
2962 if (DebugCounter::isCounterSet(VNCounter))
2963 DebugCounter::setCounterValue(VNCounter, StartingVNCounter);
2969 std::map<const Value *, CongruenceClass> BeforeIteration;
2971 for (
auto &KV : ValueToClass) {
2972 if (
auto *I = dyn_cast<Instruction>(KV.first))
2974 if (InstrToDFSNum(I) == 0)
2976 BeforeIteration.insert({KV.first, *KV.second});
2979 TouchedInstructions.set();
2980 TouchedInstructions.reset(0);
2981 iterateTouchedInstructions();
2984 for (
const auto &KV : ValueToClass) {
2985 if (
auto *I = dyn_cast<Instruction>(KV.first))
2987 if (InstrToDFSNum(I) == 0)
2991 auto *BeforeCC = &BeforeIteration.
find(KV.first)->second;
2992 auto *AfterCC = KV.second;
2995 if (!EqualClasses.
count({BeforeCC, AfterCC})) {
2996 assert(BeforeCC->isEquivalentTo(AfterCC) &&
2997 "Value number changed after main loop completed!");
2998 EqualClasses.
insert({BeforeCC, AfterCC});
3009 void NewGVN::verifyStoreExpressions()
const {
3014 std::pair<
const Value *,
3015 std::tuple<const Value *, const CongruenceClass *, Value *>>>
3017 for (
const auto &KV : ExpressionToClass) {
3018 if (
auto *SE = dyn_cast<StoreExpression>(KV.first)) {
3020 auto Res = StoreExpressionSet.insert(
3021 {SE->getOperand(0), std::make_tuple(SE->getMemoryLeader(), KV.second,
3022 SE->getStoredValue())});
3023 bool Okay = Res.second;
3028 Okay = (std::get<1>(Res.first->second) == KV.second) &&
3029 (lookupOperandLeader(std::get<2>(Res.first->second)) ==
3030 lookupOperandLeader(SE->getStoredValue()));
3031 assert(Okay &&
"Stored expression conflict exists in expression table");
3032 auto *ValueExpr = ValueToExpression.lookup(SE->getStoreInst());
3033 assert(ValueExpr && ValueExpr->equals(*SE) &&
3034 "StoreExpression in ExpressionToClass is not latest "
3035 "StoreExpression for value");
3044 void NewGVN::iterateTouchedInstructions() {
3045 unsigned int Iterations = 0;
3047 int FirstInstr = TouchedInstructions.find_first();
3049 if (FirstInstr == -1)
3051 const BasicBlock *LastBlock = getBlockForValue(InstrFromDFSNum(FirstInstr));
3052 while (TouchedInstructions.any()) {
3058 for (
unsigned InstrNum : TouchedInstructions.set_bits()) {
3062 if (InstrNum == 0) {
3063 TouchedInstructions.reset(InstrNum);
3067 Value *V = InstrFromDFSNum(InstrNum);
3068 const BasicBlock *CurrBlock = getBlockForValue(V);
3071 if (CurrBlock != LastBlock) {
3072 LastBlock = CurrBlock;
3073 bool BlockReachable = ReachableBlocks.count(CurrBlock);
3074 const auto &CurrInstRange = BlockInstRange.lookup(CurrBlock);
3077 if (!BlockReachable) {
3078 TouchedInstructions.reset(CurrInstRange.first, CurrInstRange.second);
3079 DEBUG(
dbgs() <<
"Skipping instructions in block "
3081 <<
" because it is unreachable\n");
3084 updateProcessedCount(CurrBlock);
3088 TouchedInstructions.reset(InstrNum);
3090 if (
auto *MP = dyn_cast<MemoryPhi>(V)) {
3091 DEBUG(
dbgs() <<
"Processing MemoryPhi " << *MP <<
"\n");
3092 valueNumberMemoryPhi(MP);
3093 }
else if (
auto *I = dyn_cast<Instruction>(V)) {
3094 valueNumberInstruction(I);
3098 updateProcessedCount(V);
3101 NumGVNMaxIterations =
std::max(NumGVNMaxIterations.getValue(), Iterations);
3105 bool NewGVN::runGVN() {
3106 if (DebugCounter::isCounterSet(VNCounter))
3107 StartingVNCounter = DebugCounter::getCounterValue(VNCounter);
3108 bool Changed =
false;
3110 MSSAWalker = MSSA->getWalker();
3111 SingletonDeadExpression =
new (ExpressionAllocator)
DeadExpression();
3115 unsigned ICount = 1;
3117 DFSToInstr.emplace_back(
nullptr);
3128 for (
auto &B : RPOT) {
3129 auto *Node = DT->getNode(B);
3130 assert(Node &&
"RPO and Dominator tree should have same reachability");
3131 RPOOrdering[Node] = ++
Counter;
3134 for (
auto &B : RPOT) {
3135 auto *Node = DT->getNode(B);
3136 if (Node->getChildren().size() > 1)
3139 return RPOOrdering[
A] < RPOOrdering[
B];
3146 const auto &BlockRange = assignDFSNumbers(B, ICount);
3147 BlockInstRange.insert({
B, BlockRange});
3148 ICount += BlockRange.second - BlockRange.first;
3150 initializeCongruenceClasses(F);
3152 TouchedInstructions.resize(ICount);
3156 ExpressionToClass.reserve(ICount);
3159 const auto &InstRange = BlockInstRange.lookup(&F.
getEntryBlock());
3160 TouchedInstructions.set(InstRange.first, InstRange.second);
3162 <<
" marked reachable\n");
3165 iterateTouchedInstructions();
3166 verifyMemoryCongruency();
3167 verifyIterationSettled(F);
3168 verifyStoreExpressions();
3170 Changed |= eliminateInstructions(F);
3173 for (
Instruction *ToErase : InstructionsToErase) {
3174 if (!ToErase->use_empty())
3175 ToErase->replaceAllUsesWith(UndefValue::get(ToErase->getType()));
3177 if (ToErase->getParent())
3178 ToErase->eraseFromParent();
3182 auto UnreachableBlockPred = [&](
const BasicBlock &BB) {
3183 return !ReachableBlocks.count(&BB);
3188 <<
" is unreachable\n");
3189 deleteInstructionsInBlock(&BB);
3256 void NewGVN::convertClassToDFSOrdered(
3260 for (
auto D : Dense) {
3265 assert(BB &&
"Should have figured out a basic block for value");
3273 if (
auto *SI = dyn_cast<StoreInst>(
D)) {
3276 VDDef.Def.setPointer(Leader);
3279 VDDef.Def.setInt(
true);
3282 VDDef.Def.setPointer(
D);
3285 "The dense set member should always be an instruction");
3287 VDDef.LocalNum = InstrToDFSNum(
D);
3290 if (
auto *PN = RealToTemp.lookup(Def)) {
3292 dyn_cast_or_null<PHIExpression>(ValueToExpression.lookup(Def));
3294 VDDef.Def.setInt(
false);
3295 VDDef.Def.setPointer(PN);
3301 unsigned int UseCount = 0;
3303 for (
auto &U : Def->
uses()) {
3304 if (
auto *I = dyn_cast<Instruction>(U.getUser())) {
3306 if (InstructionsToErase.count(I))
3311 if (
auto *
P = dyn_cast<PHINode>(I)) {
3312 IBlock =
P->getIncomingBlock(U);
3315 VDUse.LocalNum = InstrDFS.size() + 1;
3317 IBlock = getBlockForValue(I);
3318 VDUse.LocalNum = InstrToDFSNum(I);
3323 if (ReachableBlocks.count(IBlock) == 0)
3339 ProbablyDead.
insert(Def);
3341 UseCounts[
Def] = UseCount;
3347 void NewGVN::convertClassToLoadsAndStores(
3350 for (
auto D : Dense) {
3351 if (!isa<LoadInst>(
D) && !isa<StoreInst>(
D))
3359 VD.Def.setPointer(
D);
3362 if (
auto *I = dyn_cast<Instruction>(
D))
3363 VD.LocalNum = InstrToDFSNum(I);
3382 if (!isa<LoadInst>(I))
3394 static const unsigned KnownIDs[] = {
3395 LLVMContext::MD_tbaa, LLVMContext::MD_alias_scope,
3396 LLVMContext::MD_noalias, LLVMContext::MD_range,
3397 LLVMContext::MD_fpmath, LLVMContext::MD_invariant_load,
3398 LLVMContext::MD_invariant_group};
3407 void NewGVN::deleteInstructionsInBlock(
BasicBlock *BB) {
3408 DEBUG(
dbgs() <<
" BasicBlock Dead:" << *BB);
3409 ++NumGVNBlocksDeleted;
3413 auto StartPoint = BB->
rbegin();
3421 if (isa<LandingPadInst>(Inst))
3425 ++NumGVNInstrDeleted;
3434 void NewGVN::markInstructionForDeletion(
Instruction *I) {
3435 DEBUG(
dbgs() <<
"Marking " << *I <<
" for deletion\n");
3436 InstructionsToErase.insert(I);
3439 void NewGVN::replaceInstruction(
Instruction *I, Value *V) {
3441 DEBUG(
dbgs() <<
"Replacing " << *I <<
" with " << *V <<
"\n");
3445 markInstructionForDeletion(I);
3452 class ValueDFSStack {
3454 Value *back()
const {
return ValueStack.back(); }
3455 std::pair<int, int> dfs_back()
const {
return DFSStack.back(); }
3457 void push_back(Value *V,
int DFSIn,
int DFSOut) {
3458 ValueStack.emplace_back(V);
3459 DFSStack.emplace_back(DFSIn, DFSOut);
3461 bool empty()
const {
return DFSStack.empty(); }
3462 bool isInScope(
int DFSIn,
int DFSOut)
const {
3465 return DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second;
3468 void popUntilDFSScope(
int DFSIn,
int DFSOut) {
3471 assert(ValueStack.size() == DFSStack.size() &&
3472 "Mismatch between ValueStack and DFSStack");
3474 !DFSStack.empty() &&
3475 !(DFSIn >= DFSStack.back().first && DFSOut <= DFSStack.back().second)) {
3476 DFSStack.pop_back();
3477 ValueStack.pop_back();
3489 Value *NewGVN::findPhiOfOpsLeader(
const Expression *E,
3492 if (
auto *CE = dyn_cast<ConstantExpression>(E))
3493 return CE->getConstantValue();
3494 if (
auto *VE = dyn_cast<VariableExpression>(E))
3495 return VE->getVariableValue();
3497 auto *CC = ExpressionToClass.lookup(E);
3503 for (
auto Member : *CC) {
3510 if (MemberInst->getParent() == BB ||
3511 DT->dominates(MemberInst->getParent(), BB)) {
3518 bool NewGVN::eliminateInstructions(
Function &F) {
3542 bool AnythingReplaced =
false;
3546 DT->updateDFSNumbers();
3553 DEBUG(
dbgs() <<
"Replacing incoming value of " << PHI <<
" for block "
3555 <<
" with undef due to it being unreachable\n");
3556 Operand.set(UndefValue::get(PHI.
getType()));
3561 if ((!B.
empty() && isa<PHINode>(*B.
begin())) ||
3562 (PHIOfOpsPHIs.find(&B) != PHIOfOpsPHIs.end()))
3563 BlocksWithPhis.
insert(&B);
3565 for (
auto KV : ReachableEdges)
3566 ReachablePredCount[KV.getEnd()]++;
3567 for (
auto *BB : BlocksWithPhis)
3570 if (ReachablePredCount.
lookup(BB) !=
3572 for (
auto II = BB->
begin(); isa<PHINode>(II); ++II) {
3573 auto &PHI = cast<PHINode>(*II);
3574 ReplaceUnreachablePHIArgs(PHI, BB);
3576 for_each_found(PHIOfOpsPHIs, BB, [&](
PHINode *PHI) {
3577 ReplaceUnreachablePHIArgs(*PHI, BB);
3583 for (
auto *CC :
reverse(CongruenceClasses)) {
3584 DEBUG(
dbgs() <<
"Eliminating in congruence class " << CC->getID() <<
"\n");
3589 if (CC->isDead() || CC->empty())
3592 if (CC == TOPClass) {
3593 for (
auto M : *CC) {
3594 auto *VTE = ValueToExpression.lookup(M);
3595 if (VTE && isa<DeadExpression>(VTE))
3596 markInstructionForDeletion(cast<Instruction>(M));
3597 assert((!ReachableBlocks.count(cast<Instruction>(M)->getParent()) ||
3598 InstructionsToErase.count(cast<Instruction>(M))) &&
3599 "Everything in TOP should be unreachable or dead at this "
3605 assert(CC->getLeader() &&
"We should have had a leader");
3611 CC->getStoredValue() ? CC->getStoredValue() : CC->getLeader();
3614 for (
auto M : *CC) {
3617 if (Member == Leader || !isa<Instruction>(Member) ||
3619 MembersLeft.
insert(Member);
3622 DEBUG(
dbgs() <<
"Found replacement " << *(Leader) <<
" for " << *Member
3624 auto *I = cast<Instruction>(Member);
3625 assert(Leader != I &&
"About to accidentally remove our leader");
3626 replaceInstruction(I, Leader);
3627 AnythingReplaced =
true;
3629 CC->swap(MembersLeft);
3632 if (CC->size() != 1 || RealToTemp.lookup(Leader)) {
3637 ValueDFSStack EliminationStack;
3641 convertClassToDFSOrdered(*CC, DFSOrderedSet, UseCounts, ProbablyDead);
3645 for (
auto &VD : DFSOrderedSet) {
3646 int MemberDFSIn = VD.DFSIn;
3647 int MemberDFSOut = VD.DFSOut;
3648 Value *Def = VD.Def.getPointer();
3649 bool FromStore = VD.Def.getInt();
3654 auto *DefInst = dyn_cast_or_null<Instruction>(
Def);
3655 if (DefInst && AllTempInstructions.count(DefInst)) {
3656 auto *PN = cast<PHINode>(DefInst);
3661 AllTempInstructions.erase(PN);
3662 auto *DefBlock = getBlockForValue(Def);
3663 DEBUG(
dbgs() <<
"Inserting fully real phi of ops" << *Def
3666 PN->insertBefore(&DefBlock->front());
3668 NumGVNPHIOfOpsEliminations++;
3671 if (EliminationStack.empty()) {
3672 DEBUG(
dbgs() <<
"Elimination Stack is empty\n");
3674 DEBUG(
dbgs() <<
"Elimination Stack Top DFS numbers are ("
3675 << EliminationStack.dfs_back().first <<
","
3676 << EliminationStack.dfs_back().second <<
")\n");
3679 DEBUG(
dbgs() <<
"Current DFS numbers are (" << MemberDFSIn <<
","
3680 << MemberDFSOut <<
")\n");
3694 bool ShouldPush = Def && EliminationStack.empty();
3696 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut);
3698 if (OutOfScope || ShouldPush) {
3700 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3701 bool ShouldPush = Def && EliminationStack.empty();
3703 EliminationStack.push_back(Def, MemberDFSIn, MemberDFSOut);
3722 if (!EliminationStack.empty() && Def != EliminationStack.back() &&
3723 isa<Instruction>(
Def) && !FromStore)
3724 markInstructionForDeletion(cast<Instruction>(Def));
3730 assert(isa<Instruction>(U->get()) &&
3731 "Current def should have been an instruction");
3732 assert(isa<Instruction>(U->getUser()) &&
3733 "Current user should have been an instruction");
3739 Instruction *InstUse = cast<Instruction>(U->getUser());
3740 if (InstructionsToErase.count(InstUse)) {
3741 auto &UseCount = UseCounts[U->get()];
3742 if (--UseCount == 0) {
3743 ProbablyDead.
insert(cast<Instruction>(U->get()));
3749 if (EliminationStack.empty())
3752 Value *DominatingLeader = EliminationStack.back();
3755 if (II && II->getIntrinsicID() == Intrinsic::ssa_copy)
3756 DominatingLeader = II->getOperand(0);
3759 if (U->get() == DominatingLeader)
3761 DEBUG(
dbgs() <<
"Found replacement " << *DominatingLeader <<
" for "
3762 << *U->get() <<
" in " << *(U->getUser()) <<
"\n");
3767 auto *ReplacedInst = cast<Instruction>(U->get());
3768 auto *PI = PredInfo->getPredicateInfoFor(ReplacedInst);
3769 if (!PI || DominatingLeader != PI->OriginalOp)
3771 U->set(DominatingLeader);
3774 auto &LeaderUseCount = UseCounts[DominatingLeader];
3776 if (LeaderUseCount == 0 && isa<Instruction>(DominatingLeader))
3777 ProbablyDead.
erase(cast<Instruction>(DominatingLeader));
3778 if (LeaderUseCount == 0 && II)
3781 AnythingReplaced =
true;
3788 for (
auto *I : ProbablyDead)
3790 markInstructionForDeletion(I);
3794 for (
auto *Member : *CC)
3795 if (!isa<Instruction>(Member) ||
3796 !InstructionsToErase.count(cast<Instruction>(Member)))
3797 MembersLeft.
insert(Member);
3798 CC->swap(MembersLeft);
3801 if (CC->getStoreCount() > 0) {
3802 convertClassToLoadsAndStores(*CC, PossibleDeadStores);
3803 std::sort(PossibleDeadStores.begin(), PossibleDeadStores.end());
3804 ValueDFSStack EliminationStack;
3805 for (
auto &VD : PossibleDeadStores) {
3806 int MemberDFSIn = VD.DFSIn;
3807 int MemberDFSOut = VD.DFSOut;
3808 Instruction *Member = cast<Instruction>(VD.Def.getPointer());
3809 if (EliminationStack.empty() ||
3810 !EliminationStack.isInScope(MemberDFSIn, MemberDFSOut)) {
3812 EliminationStack.popUntilDFSScope(MemberDFSIn, MemberDFSOut);
3813 if (EliminationStack.empty()) {
3814 EliminationStack.push_back(Member, MemberDFSIn, MemberDFSOut);
3819 if (isa<LoadInst>(Member))
3821 assert(!EliminationStack.empty());
3822 Instruction *Leader = cast<Instruction>(EliminationStack.back());
3826 DEBUG(
dbgs() <<
"Marking dead store " << *Member
3827 <<
" that is dominated by " << *Leader <<
"\n");
3828 markInstructionForDeletion(Member);
3834 return AnythingReplaced;
3842 unsigned int NewGVN::getRank(
const Value *V)
const {
3846 if (isa<ConstantExpr>(V))
3848 if (isa<UndefValue>(V))
3850 if (isa<Constant>(V))
3852 else if (
auto *
A = dyn_cast<Argument>(V))
3853 return 3 +
A->getArgNo();
3857 unsigned Result = InstrToDFSNum(V);
3859 return 4 + NumFuncArgs + Result;
3866 bool NewGVN::shouldSwapOperands(
const Value *
A,
const Value *B)
const {
3870 return std::make_pair(getRank(A), A) > std::make_pair(getRank(B), B);
3895 bool NewGVNLegacyPass::runOnFunction(
Function &F) {
3896 if (skipFunction(F))
3898 return NewGVN(F, &getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
3899 &getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
3900 &getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(),
3901 &getAnalysis<AAResultsWrapperPass>().getAAResults(),
3902 &getAnalysis<MemorySSAWrapperPass>().getMSSA(),
3918 char NewGVNLegacyPass::
ID = 0;
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.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
static ConstantInt * getFalse(LLVMContext &Context)
This class is the base class for the comparison instructions.
INITIALIZE_PASS_BEGIN(NewGVNLegacyPass,"newgvn","Global Value Numbering", false, false) INITIALIZE_PASS_END(NewGVNLegacyPass
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...
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...
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
unsigned getStoreCount() const
void dropAllReferences()
Drop all references to operands.
MemoryMemberSet::const_iterator memory_end() const
STATISTIC(NumFunctions,"Total number of functions")
static bool equalsLoadStoreHelper(const T &LHS, const Expression &RHS)
newgvn Controls which instructions we create phi of ops static for cl::opt< bool > EnableStoreRefinement("enable-store-refinement", cl::init(false), cl::Hidden)
static bool isEqual(const ExactEqualsExpression &LHS, const Expression *RHS)
This is the interface for a simple mod/ref and alias analysis over globals.
MemberSet::const_iterator begin() const
Value * getLeader() const
static bool okayForPHIOfOps(const Instruction *I)
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
Implements a dense probed hash-table based set.
unsigned getNumOperands() const
hash_code getComputedHash() const
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
This class represents a function call, abstracting a target machine's calling convention.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of .assume calls within a function.
Represents a read-write access to memory, whether it is a must-alias, or a may-alias.
void addPossibleNextLeader(std::pair< Value *, unsigned int > LeaderPair)
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...
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
bool definesNoMemory() const
Analysis pass which computes a DominatorTree.
An instruction for reading from memory.
reverse_iterator rbegin()
hash_code getComputedHash() const
Constant * getConstantMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, const DataLayout &DL)
ExactEqualsExpression(const Expression &E)
This file defines the MallocAllocator and BumpPtrAllocator interfaces.
unsigned getOpcode() const
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
void insert(MemberType *M)
iterator begin()
Instruction iterator methods.
void Start(const Instruction *Start)
static bool isImpliedFalseByMatchingCmp(Predicate Pred1, Predicate Pred2)
Determine if Pred1 implies Pred2 is false when two compares have matching operands.
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
Legacy analysis pass which computes MemorySSA.
A Use represents the edge between a Value definition and its users.
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.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
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
Windows NT (Windows on ARM)
This file provides an implementation of debug counters.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
mapped_iterator< ItTy, FuncTy > map_iterator(const ItTy &I, FuncTy F)
void setLeader(Value *Leader)
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()))
BasicBlock * getBlock() const
Value * SimplifyCmpInst(unsigned Predicate, Value *LHS, Value *RHS, const SimplifyQuery &Q)
Given operands for a CmpInst, fold the result or return null.
static int getID(struct InternalInstruction *insn, const void *miiArg)
void andIRFlags(const Value *V)
Logical 'and' of any supported wrapping, exact, and fast-math flags of V and this instruction...
BasicBlock * getSuccessor(unsigned i) const
Base class for the actual dominator tree node.
ArrayRef - Represent a constant reference to an array (0 or more elements consecutively in memory)...
An instruction for storing to memory.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
CongruenceClass(unsigned ID, Value *Leader, const Expression *E)
This is the generic walker interface for walkers of MemorySSA.
FunctionPass * createNewGVNPass()
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
const Expression * getDefiningExpr() const
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
static const Expression * getEmptyKey()
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...
MemberSet::const_iterator end() const
initializer< Ty > init(const Ty &Val)
Value * SimplifySelectInst(Value *Cond, Value *TrueVal, Value *FalseVal, const SimplifyQuery &Q)
Given operands for a SelectInst, fold the result or return null.
MemoryMemberSet::const_iterator memory_begin() const
Control flow instructions. These all have token chains.
Subclasses of this class are all able to terminate a basic block.
Unify divergent function exit nodes
A set of analyses that are preserved following a run of a transformation pass.
std::enable_if<!std::is_array< T >::value, std::unique_ptr< T > >::type make_unique(Args &&...args)
Constructs a new T() with the given args and returns a unique_ptr<T> which owns the object...
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.
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
Constant * getConstantLoadValueForLoad(Constant *SrcVal, unsigned Offset, Type *LoadTy, const DataLayout &DL)
A manager for alias analyses.
DEBUG_COUNTER(VNCounter,"newgvn-vn","Controls which instructions are value numbered") DEBUG_COUNTER(PHIOfOpsCounter
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.
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...
Value * SimplifyCastInst(unsigned CastOpc, Value *Op, Type *Ty, const SimplifyQuery &Q)
Given operands for a CastInst, fold the result or return null.
unsigned getDFSNumIn() const
getDFSNumIn/getDFSNumOut - These return the DFS visitation order for nodes in the dominator tree...
Represent the analysis usage information of a pass.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
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...
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
Analysis pass providing a never-invalidated alias analysis result.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
unsigned getValueID() const
Return an ID for the concrete type of this object.
static const unsigned End
This file provides the interface for LLVM's Global Value Numbering pass.
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
FunctionPass class - This class is used to implement most global optimizations.
Value * getOperand(unsigned i) const
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
bool isCommutative() const
Return true if the instruction is commutative:
Predicate getPredicate() const
Return the predicate for this instruction.
bool memory_empty() const
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.
const SmallPtrSetImpl< const Value * > & getComponentFor(const Value *V) const
static const Expression * getTombstoneKey()
This file implements the PredicateInfo analysis, which creates an Extended SSA form for operations us...
void memory_insert(const MemoryMemberType *M)
const MemoryAccess * getMemoryLeader() const
bool isTerminator() const
bool isConditional() const
DOTGraphTraits - Template class that can be specialized to customize how graphs are converted to 'dot...
const Value * DoPHITranslation(const BasicBlock *CurBB, const BasicBlock *PredBB) const
Translate PHI node to its predecessor from the given basic block.
SmallPtrSetIterator - This implements a const_iterator for SmallPtrSet.
A function analysis which provides an AssumptionCache.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
Value * getStoredValue() const
This is the shared class of boolean and integer constants.
void setOpcode(unsigned opcode)
bool erase(PtrType Ptr)
erase - If the set contains the specified pointer, remove it and return true, otherwise return false...
iterator_range< MemoryMemberSet::const_iterator > memory() const
Type * getType() const
All values are typed, get the type of this value.
Provides information about what library functions are available for the current target.
bool operator<(const ValueDFS &Other) const
Predicate
Predicate - These are "(BI << 5) | BO" for various predicates.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
unsigned memory_size() const
bool isTrueWhenEqual() const
This is just a convenience.
An analysis that produces MemorySSA for a function.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
bool isZero() const
This is just a convenience method to make client code smaller for a common code.
const BasicBlock & getEntryBlock() const
static ConstantInt * getTrue(LLVMContext &Context)
BasicBlock * getSuccessor(unsigned idx) const
Return the specified successor.
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.
const std::pair< Value *, unsigned int > & getNextLeader() const
Encapsulates PredicateInfo, including all data associated with memory accesses.
A range adaptor for a pair of iterators.
static bool alwaysAvailable(Value *V)
void setStoredValue(Value *Leader)
Class that has the common methods + fields of memory uses/defs.
void erase(MemberType *M)
iterator_range< user_iterator > users()
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 ...
void setMemoryLeader(const MemoryAccess *Leader)
llvm_unreachable("Unknown RegBank!")
unsigned getDFSNumOut() const
BasicBlock * getIncomingBlock(unsigned I) const
Return incoming basic block number i.
Value * SimplifyGEPInst(Type *SrcTy, ArrayRef< Value * > Ops, const SimplifyQuery &Q)
Given operands for a GetElementPtrInst, fold the result or return null.
CongruenceClass(unsigned ID)
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
void swap(MemberSet &Other)
Value * getCondition() const
void emplace_back(ArgTypes &&...Args)
unsigned getAlignment() const
Return the alignment of the access that is being performed.
This file provides utility analysis objects describing memory locations.
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...
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
iterator find(const_arg_type_t< ValueT > V)
Value * getOperand(unsigned N) const
bool operator==(const Expression &Other) const
bool isEquivalentTo(const CongruenceClass *Other) const
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
void preserve()
Mark an analysis as preserved.
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)
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
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...
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
Instruction * getMemoryInst() const
Get the instruction that this MemoryUse represents.
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())
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...
static bool isEqual(const Expression *LHS, const Expression *RHS)
LLVMContext & getContext() const
Get the context in which this basic block lives.
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.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
The header file for the GVN pass that contains expression handling classes.
virtual bool runOnFunction(Function &F)=0
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
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...
This file exposes an interface to building/using memory SSA to walk memory instructions using a use/d...
PointerType * getPointerTo(unsigned AddrSpace=0) const
Return a pointer to the current type.
inst_range instructions(Function *F)
A container for analyses that lazily runs them and caches their results.
void memory_erase(const MemoryMemberType *M)
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
Represents phi nodes for memory accesses.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static unsigned getHashValue(const Expression *E)
op_range incoming_values()
void op_push_back(Value *Arg)
Value * getPointerOperand()
void combineMetadata(Instruction *K, const Instruction *J, ArrayRef< unsigned > KnownIDs)
Combine the metadata of two instructions so that K can replace J.
static void patchReplacementInstruction(Instruction *I, Value *Repl)
const BasicBlock * getParent() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
void allocateOperands(RecyclerType &Recycler, BumpPtrAllocator &Allocator)
iterator_range< arg_iterator > args()
A wrapper class for inspecting calls to intrinsic functions.
bool isVoidTy() const
Return true if this is 'void'.