42 #include "llvm/Config/llvm-config.h" 90 #define DEBUG_TYPE "gvn" 92 STATISTIC(NumGVNInstr,
"Number of instructions deleted");
93 STATISTIC(NumGVNLoad,
"Number of loads deleted");
94 STATISTIC(NumGVNPRE,
"Number of instructions PRE'd");
95 STATISTIC(NumGVNBlocks,
"Number of blocks merged");
96 STATISTIC(NumGVNSimpl,
"Number of instructions simplified");
97 STATISTIC(NumGVNEqProp,
"Number of equalities propagated");
98 STATISTIC(NumPRELoad,
"Number of loads PRE'd");
108 cl::desc(
"Max recurse depth in GVN (default = 1000)"));
112 cl::desc(
"Max number of dependences to attempt Load PRE (default = 100)"));
117 bool commutative =
false;
123 if (opcode != other.
opcode)
125 if (opcode == ~0U || opcode == ~1U)
127 if (type != other.
type)
181 Res.
Val.setPointer(V);
182 Res.
Val.setInt(SimpleVal);
189 Res.
Val.setPointer(MI);
190 Res.
Val.setInt(MemIntrin);
197 Res.
Val.setPointer(LI);
198 Res.
Val.setInt(LoadVal);
205 Res.
Val.setPointer(
nullptr);
206 Res.
Val.setInt(UndefVal);
217 assert(isSimpleValue() &&
"Wrong accessor");
222 assert(isCoercedLoadValue() &&
"Wrong accessor");
227 assert(isMemIntrinValue() &&
"Wrong accessor");
249 Res.
AV = std::move(AV);
279 e.varargs.push_back(lookupOrAdd(*OI));
286 if (e.varargs[0] > e.varargs[1])
288 e.commutative =
true;
291 if (
CmpInst *
C = dyn_cast<CmpInst>(I)) {
294 if (e.varargs[0] > e.varargs[1]) {
299 e.commutative =
true;
303 e.varargs.push_back(*II);
312 assert((Opcode == Instruction::ICmp || Opcode == Instruction::FCmp) &&
313 "Not a comparison!");
316 e.varargs.push_back(lookupOrAdd(LHS));
317 e.varargs.push_back(lookupOrAdd(RHS));
320 if (e.varargs[0] > e.varargs[1]) {
324 e.opcode = (Opcode << 8) | Predicate;
325 e.commutative =
true;
330 assert(EI &&
"Not an ExtractValueInst?");
341 e.varargs.push_back(lookupOrAdd(WO->
getLHS()));
342 e.varargs.push_back(lookupOrAdd(WO->
getRHS()));
351 e.varargs.push_back(lookupOrAdd(*OI));
355 e.varargs.push_back(*II);
372 valueNumbering.insert(std::make_pair(V, num));
373 if (
PHINode *PN = dyn_cast<PHINode>(V))
374 NumberingPhi[num] = PN;
378 if (AA->doesNotAccessMemory(C)) {
380 uint32_t e = assignExpNewValueNum(exp).first;
381 valueNumbering[
C] =
e;
383 }
else if (MD && AA->onlyReadsMemory(C)) {
385 auto ValNum = assignExpNewValueNum(exp);
387 valueNumbering[
C] = ValNum.first;
394 valueNumbering[
C] = nextValueNumber;
395 return nextValueNumber++;
398 if (local_dep.
isDef()) {
402 valueNumbering[
C] = nextValueNumber;
403 return nextValueNumber++;
410 valueNumbering[
C] = nextValueNumber;
411 return nextValueNumber++;
415 uint32_t v = lookupOrAdd(local_cdep);
416 valueNumbering[
C] = v;
422 MD->getNonLocalCallDependency(C);
428 for (
unsigned i = 0,
e = deps.size(); i !=
e; ++i) {
442 if (NonLocalDepCall && DT->properlyDominates(I->
getBB(), C->
getParent())){
443 cdep = NonLocalDepCall;
452 valueNumbering[
C] = nextValueNumber;
453 return nextValueNumber++;
457 valueNumbering[
C] = nextValueNumber;
458 return nextValueNumber++;
464 valueNumbering[
C] = nextValueNumber;
465 return nextValueNumber++;
470 valueNumbering[
C] = v;
473 valueNumbering[
C] = nextValueNumber;
474 return nextValueNumber++;
485 if (VI != valueNumbering.end())
488 if (!isa<Instruction>(V)) {
489 valueNumbering[V] = nextValueNumber;
490 return nextValueNumber++;
497 return lookupOrAddCall(cast<CallInst>(I));
498 case Instruction::FNeg:
500 case Instruction::FAdd:
501 case Instruction::Sub:
502 case Instruction::FSub:
503 case Instruction::Mul:
504 case Instruction::FMul:
505 case Instruction::UDiv:
506 case Instruction::SDiv:
507 case Instruction::FDiv:
508 case Instruction::URem:
509 case Instruction::SRem:
510 case Instruction::FRem:
511 case Instruction::Shl:
512 case Instruction::LShr:
513 case Instruction::AShr:
514 case Instruction::And:
515 case Instruction::Or:
516 case Instruction::Xor:
517 case Instruction::ICmp:
518 case Instruction::FCmp:
519 case Instruction::Trunc:
520 case Instruction::ZExt:
521 case Instruction::SExt:
522 case Instruction::FPToUI:
523 case Instruction::FPToSI:
524 case Instruction::UIToFP:
525 case Instruction::SIToFP:
526 case Instruction::FPTrunc:
527 case Instruction::FPExt:
528 case Instruction::PtrToInt:
529 case Instruction::IntToPtr:
530 case Instruction::AddrSpaceCast:
531 case Instruction::BitCast:
533 case Instruction::ExtractElement:
534 case Instruction::InsertElement:
535 case Instruction::ShuffleVector:
536 case Instruction::InsertValue:
537 case Instruction::GetElementPtr:
540 case Instruction::ExtractValue:
541 exp = createExtractvalueExpr(cast<ExtractValueInst>(I));
543 case Instruction::PHI:
544 valueNumbering[V] = nextValueNumber;
545 NumberingPhi[nextValueNumber] = cast<PHINode>(V);
546 return nextValueNumber++;
548 valueNumbering[V] = nextValueNumber;
549 return nextValueNumber++;
552 uint32_t e = assignExpNewValueNum(exp).first;
553 valueNumbering[V] =
e;
562 assert(VI != valueNumbering.end() &&
"Value not numbered?");
565 return (VI != valueNumbering.end()) ? VI->second : 0;
575 Expression exp = createCmpExpr(Opcode, Predicate, LHS, RHS);
576 return assignExpNewValueNum(exp).first;
581 valueNumbering.clear();
582 expressionNumbering.clear();
583 NumberingPhi.clear();
584 PhiTranslateTable.clear();
593 uint32_t Num = valueNumbering.lookup(V);
594 valueNumbering.erase(V);
597 NumberingPhi.erase(Num);
604 I = valueNumbering.begin(),
E = valueNumbering.end(); I !=
E; ++
I) {
605 assert(I->first != V &&
"Inst still occurs in value numbering map!");
625 bool Changed =
runImpl(F, AC, DT, TLI, AA, &MemDep, LI, &ORE);
637 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 641 E = d.
end(); I !=
E; ++
I) {
642 errs() << I->first <<
"\n";
667 std::pair<DenseMap<BasicBlock*, char>::iterator,
bool> IV =
668 FullyAvailableBlocks.
insert(std::make_pair(BB, 2));
674 if (IV.first->second == 2)
675 IV.first->second = 3;
676 return IV.first->second != 0;
684 goto SpeculationFailure;
686 for (; PI != PE; ++PI)
691 goto SpeculationFailure;
699 char &BBVal = FullyAvailableBlocks[BB];
717 char &EntryVal = FullyAvailableBlocks[Entry];
718 if (EntryVal == 0)
continue;
724 }
while (!BBWorklist.
empty());
737 if (ValuesPerBlock.
size() == 1 &&
740 assert(!ValuesPerBlock[0].AV.isUndefValue() &&
741 "Dead BB dominate this block");
742 return ValuesPerBlock[0].MaterializeAdjustedValue(LI, gvn);
761 ((AV.AV.isSimpleValue() && AV.AV.getSimpleValue() == LI) ||
762 (AV.AV.isCoercedLoadValue() && AV.AV.getCoercedLoadValue() == LI)))
778 if (isSimpleValue()) {
779 Res = getSimpleValue();
780 if (Res->
getType() != LoadTy) {
784 <<
" " << *getSimpleValue() <<
'\n' 788 }
else if (isCoercedLoadValue()) {
800 LLVM_DEBUG(
dbgs() <<
"GVN COERCED NONLOCAL LOAD:\nOffset: " << Offset
801 <<
" " << *getCoercedLoadValue() <<
'\n' 805 }
else if (isMemIntrinValue()) {
809 <<
" " << *getMemIntrinValue() <<
'\n' 813 assert(isUndefValue() &&
"Should be UndefVal");
817 assert(Res &&
"failed to materialize?");
823 return II->getIntrinsicID() == Intrinsic::lifetime_start;
834 User *OtherAccess =
nullptr;
837 R <<
"load of type " <<
NV(
"Type", LI->
getType()) <<
" not eliminated" 841 if (U != LI && (isa<LoadInst>(U) || isa<StoreInst>(U)) &&
842 DT->
dominates(cast<Instruction>(U), LI)) {
847 OtherAccess =
nullptr;
853 R <<
" in favor of " <<
NV(
"OtherAccess", OtherAccess);
855 R <<
" because it is clobbered by " <<
NV(
"ClobberedBy", DepInfo.
getInst());
863 "expected a local dependence");
873 if (
StoreInst *DepSI = dyn_cast<StoreInst>(DepInst)) {
875 if (Address && LI->
isAtomic() <= DepSI->isAtomic()) {
889 if (
LoadInst *DepLI = dyn_cast<LoadInst>(DepInst)) {
893 if (DepLI != LI && Address && LI->
isAtomic() <= DepLI->isAtomic()) {
906 if (
MemIntrinsic *DepMI = dyn_cast<MemIntrinsic>(DepInst)) {
920 dbgs() <<
" is clobbered by " << *DepInst <<
'\n';);
942 if (
StoreInst *S = dyn_cast<StoreInst>(DepInst)) {
958 if (
LoadInst *
LD = dyn_cast<LoadInst>(DepInst)) {
977 dbgs() <<
" has unknown def " << *DepInst <<
'\n';);
981 void GVN::AnalyzeLoadAvailability(
LoadInst *LI, LoadDepVect &Deps,
982 AvailValInBlkVect &ValuesPerBlock,
983 UnavailBlkVect &UnavailableBlocks) {
988 unsigned NumDeps = Deps.size();
989 for (
unsigned i = 0,
e = NumDeps; i !=
e; ++i) {
993 if (DeadBlocks.count(DepBB)) {
1001 UnavailableBlocks.push_back(DepBB);
1008 Value *Address = Deps[i].getAddress();
1011 if (AnalyzeLoadAvailability(LI, DepInfo, Address, AV)) {
1018 UnavailableBlocks.push_back(DepBB);
1022 assert(NumDeps == ValuesPerBlock.size() + UnavailableBlocks.size() &&
1023 "post condition violation");
1026 bool GVN::PerformLoadPRE(
LoadInst *LI, AvailValInBlkVect &ValuesPerBlock,
1027 UnavailBlkVect &UnavailableBlocks) {
1037 UnavailableBlocks.end());
1060 if (!IsSafeToSpeculativelyExecute && ICF->isDominatedByICFIFromSameBlock(LI))
1064 if (TmpBB == LoadBB)
1066 if (Blockers.count(TmpBB))
1078 if (!IsSafeToSpeculativelyExecute && ICF->hasICF(TmpBB))
1090 FullyAvailableBlocks[AV.BB] =
true;
1091 for (
BasicBlock *UnavailableBB : UnavailableBlocks)
1092 FullyAvailableBlocks[UnavailableBB] =
false;
1098 if (Pred->getTerminator()->isEHPad()) {
1100 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD PREDECESSOR '" 1101 << Pred->getName() <<
"': " << *LI <<
'\n');
1109 if (Pred->getTerminator()->getNumSuccessors() != 1) {
1110 if (isa<IndirectBrInst>(Pred->getTerminator())) {
1112 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF INDBR CRITICAL EDGE '" 1113 << Pred->getName() <<
"': " << *LI <<
'\n');
1118 if (isa<CallBrInst>(Pred->getTerminator())) {
1120 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF CALLBR CRITICAL EDGE '" 1121 << Pred->getName() <<
"': " << *LI <<
'\n');
1125 if (LoadBB->isEHPad()) {
1127 dbgs() <<
"COULD NOT PRE LOAD BECAUSE OF AN EH PAD CRITICAL EDGE '" 1128 << Pred->getName() <<
"': " << *LI <<
'\n');
1135 PredLoads[Pred] =
nullptr;
1140 unsigned NumUnavailablePreds = PredLoads.
size() + CriticalEdgePred.
size();
1141 assert(NumUnavailablePreds != 0 &&
1142 "Fully available value should already be eliminated!");
1148 if (NumUnavailablePreds != 1)
1152 for (
BasicBlock *OrigPred : CriticalEdgePred) {
1153 BasicBlock *NewPred = splitCriticalEdges(OrigPred, LoadBB);
1154 assert(!PredLoads.
count(OrigPred) &&
"Split edges shouldn't be in map!");
1155 PredLoads[NewPred] =
nullptr;
1156 LLVM_DEBUG(
dbgs() <<
"Split critical edge " << OrigPred->getName() <<
"->" 1157 << LoadBB->getName() <<
'\n');
1161 bool CanDoPRE =
true;
1164 for (
auto &PredLoad : PredLoads) {
1165 BasicBlock *UnavailablePred = PredLoad.first;
1177 while (Cur != LoadBB) {
1202 PredLoad.second = LoadPtr;
1206 while (!NewInsts.
empty()) {
1216 return !CriticalEdgePred.empty();
1224 <<
"INSERTED " << NewInsts.
size() <<
" INSTS: " << *NewInsts.
back()
1242 for (
const auto &PredLoad : PredLoads) {
1243 BasicBlock *UnavailablePred = PredLoad.first;
1244 Value *LoadPtr = PredLoad.second;
1256 NewLoad->setAAMetadata(Tags);
1258 if (
auto *MD = LI->
getMetadata(LLVMContext::MD_invariant_load))
1259 NewLoad->setMetadata(LLVMContext::MD_invariant_load, MD);
1260 if (
auto *InvGroupMD = LI->
getMetadata(LLVMContext::MD_invariant_group))
1261 NewLoad->setMetadata(LLVMContext::MD_invariant_group, InvGroupMD);
1262 if (
auto *RangeMD = LI->
getMetadata(LLVMContext::MD_range))
1263 NewLoad->setMetadata(LLVMContext::MD_range, RangeMD);
1274 MD->invalidateCachedPointerInfo(LoadPtr);
1281 if (isa<PHINode>(V))
1286 MD->invalidateCachedPointerInfo(V);
1287 markInstructionForDeletion(LI);
1290 <<
"load eliminated by PRE";
1298 using namespace ore;
1302 <<
"load of type " <<
NV(
"Type", LI->
getType()) <<
" eliminated" 1304 <<
NV(
"InfavorOfValue", AvailableValue);
1310 bool GVN::processNonLocalLoad(
LoadInst *LI) {
1313 Attribute::SanitizeAddress) ||
1315 Attribute::SanitizeHWAddress))
1320 MD->getNonLocalPointerDependency(LI, Deps);
1325 unsigned NumDeps = Deps.size();
1332 !Deps[0].getResult().isDef() && !Deps[0].getResult().isClobber()) {
1334 dbgs() <<
" has unknown dependencies\n";);
1341 OE =
GEP->idx_end();
1343 if (
Instruction *I = dyn_cast<Instruction>(OI->get()))
1344 performScalarPRE(I);
1348 AvailValInBlkVect ValuesPerBlock;
1349 UnavailBlkVect UnavailableBlocks;
1350 AnalyzeLoadAvailability(LI, Deps, ValuesPerBlock, UnavailableBlocks);
1354 if (ValuesPerBlock.empty())
1362 if (UnavailableBlocks.empty()) {
1363 LLVM_DEBUG(
dbgs() <<
"GVN REMOVING NONLOCAL LOAD: " << *LI <<
'\n');
1369 if (isa<PHINode>(V))
1378 MD->invalidateCachedPointerInfo(V);
1379 markInstructionForDeletion(LI);
1389 return PerformLoadPRE(LI, ValuesPerBlock, UnavailableBlocks);
1393 if (Cmp->
getPredicate() == CmpInst::Predicate::ICMP_EQ)
1399 if (Cmp->
getPredicate() == CmpInst::Predicate::FCMP_OEQ ||
1400 (Cmp->
getPredicate() == CmpInst::Predicate::FCMP_UEQ &&
1409 if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->
isZero())
1411 if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->
isZero())
1419 if (Cmp->
getPredicate() == CmpInst::Predicate::ICMP_NE)
1425 if ((Cmp->
getPredicate() == CmpInst::Predicate::FCMP_ONE &&
1435 if (isa<ConstantFP>(LHS) && !cast<ConstantFP>(LHS)->
isZero())
1437 if (isa<ConstantFP>(RHS) && !cast<ConstantFP>(RHS)->
isZero())
1447 if (isa<Instruction>(U) &&
1448 cast<Instruction>(U)->
getParent() == BB)
1453 bool GVN::processAssumeIntrinsic(
IntrinsicInst *IntrinsicI) {
1455 "This function can only be called with llvm.assume intrinsic");
1458 if (
ConstantInt *Cond = dyn_cast<ConstantInt>(V)) {
1459 if (Cond->isZero()) {
1468 markInstructionForDeletion(IntrinsicI);
1470 }
else if (isa<Constant>(V)) {
1478 bool Changed =
false;
1485 Changed |= propagateEquality(V, True, Edge,
false);
1491 ReplaceOperandsWithMap[V] = True;
1508 if (
auto *CmpI = dyn_cast<CmpInst>(V)) {
1510 Value *CmpLHS = CmpI->getOperand(0);
1511 Value *CmpRHS = CmpI->getOperand(1);
1517 if (isa<Constant>(CmpLHS) && !isa<Constant>(CmpRHS))
1519 if (!isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))
1521 if ((isa<Argument>(CmpLHS) && isa<Argument>(CmpRHS)) ||
1522 (isa<Instruction>(CmpLHS) && isa<Instruction>(CmpRHS))) {
1525 uint32_t LVN = VN.lookupOrAdd(CmpLHS);
1526 uint32_t RVN = VN.lookupOrAdd(CmpRHS);
1533 if (isa<Constant>(CmpLHS) && isa<Constant>(CmpRHS))
1537 << *CmpLHS <<
" with " 1538 << *CmpRHS <<
" in block " 1544 ReplaceOperandsWithMap[CmpLHS] = CmpRHS;
1562 bool GVN::processLoad(
LoadInst *L) {
1571 markInstructionForDeletion(L);
1580 return processNonLocalLoad(L);
1588 dbgs() <<
" has unknown dependence\n";);
1598 markInstructionForDeletion(L);
1604 MD->invalidateCachedPointerInfo(AvailableValue);
1613 std::pair<uint32_t, bool>
1614 GVN::ValueTable::assignExpNewValueNum(Expression &Exp) {
1616 bool CreateNewValNum = !
e;
1617 if (CreateNewValNum) {
1619 if (ExprIdx.size() < nextValueNumber + 1)
1620 ExprIdx.resize(nextValueNumber * 2);
1621 e = nextValueNumber;
1622 ExprIdx[nextValueNumber++] = nextExprNumber++;
1624 return {
e, CreateNewValNum};
1631 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
1632 while (Vals && Vals->BB == BB)
1641 auto FindRes = PhiTranslateTable.find({Num, Pred});
1642 if (FindRes != PhiTranslateTable.end())
1643 return FindRes->second;
1644 uint32_t NewNum = phiTranslateImpl(Pred, PhiBlock, Num, Gvn);
1645 PhiTranslateTable.insert({{Num, Pred}, NewNum});
1655 LeaderTableEntry *Vals = &Gvn.LeaderTable[Num];
1658 if (Call && Call->
getParent() == PhiBlock)
1663 if (AA->doesNotAccessMemory(Call))
1666 if (!MD || !AA->onlyReadsMemory(Call))
1674 MD->getNonLocalCallDependency(Call);
1677 for (
unsigned i = 0; i < deps.size(); i++) {
1678 if (deps[i].getResult().isNonFuncLocal())
1689 if (
PHINode *PN = NumberingPhi[Num]) {
1690 for (
unsigned i = 0; i != PN->getNumIncomingValues(); ++i) {
1691 if (PN->getParent() == PhiBlock && PN->getIncomingBlock(i) == Pred)
1701 if (!areAllValsInBB(Num, PhiBlock, Gvn))
1704 if (Num >= ExprIdx.size() || ExprIdx[Num] == 0)
1708 for (
unsigned i = 0; i < Exp.
varargs.
size(); i++) {
1712 if ((i > 1 && Exp.
opcode == Instruction::InsertValue) ||
1713 (i > 0 && Exp.
opcode == Instruction::ExtractValue))
1715 Exp.
varargs[i] = phiTranslate(Pred, PhiBlock, Exp.
varargs[i], Gvn);
1723 if (Opcode == Instruction::ICmp || Opcode == Instruction::FCmp)
1724 Exp.
opcode = (Opcode << 8) |
1726 static_cast<CmpInst::Predicate>(Exp.
opcode & 255));
1730 if (
uint32_t NewNum = expressionNumbering[Exp]) {
1732 return areCallValsEqual(Num, NewNum, Pred, PhiBlock, Gvn) ? NewNum : Num;
1743 auto FindRes = PhiTranslateTable.find({Num, Pred});
1744 if (FindRes != PhiTranslateTable.end())
1745 PhiTranslateTable.erase(FindRes);
1755 LeaderTableEntry Vals = LeaderTable[num];
1756 if (!Vals.Val)
return nullptr;
1758 Value *Val =
nullptr;
1759 if (DT->dominates(Vals.BB, BB)) {
1761 if (isa<Constant>(Val))
return Val;
1764 LeaderTableEntry* Next = Vals.Next;
1766 if (DT->dominates(Next->BB, BB)) {
1767 if (isa<Constant>(Next->Val))
return Next->Val;
1768 if (!Val) Val = Next->Val;
1789 "No edge between these basic blocks!");
1790 return Pred !=
nullptr;
1793 void GVN::assignBlockRPONumber(
Function &
F) {
1794 BlockRPONumber.clear();
1798 BlockRPONumber[BB] = NextBlockNumber++;
1799 InvalidBlockRPONumbers =
false;
1802 bool GVN::replaceOperandsForInBlockEquality(
Instruction *Instr)
const {
1803 bool Changed =
false;
1804 for (
unsigned OpNum = 0; OpNum < Instr->
getNumOperands(); ++OpNum) {
1806 auto it = ReplaceOperandsWithMap.find(Operand);
1807 if (it != ReplaceOperandsWithMap.end()) {
1809 << *it->second <<
" in instruction " << *Instr <<
'\n');
1823 bool DominatesByEdge) {
1825 Worklist.
push_back(std::make_pair(LHS, RHS));
1826 bool Changed =
false;
1831 while (!Worklist.
empty()) {
1832 std::pair<Value*, Value*> Item = Worklist.
pop_back_val();
1833 LHS = Item.first; RHS = Item.second;
1840 if (isa<Constant>(LHS) && isa<Constant>(RHS))
1844 if (isa<Constant>(LHS) || (isa<Argument>(LHS) && !isa<Constant>(RHS)))
1846 assert((isa<Argument>(LHS) || isa<Instruction>(LHS)) &&
"Unexpected value!");
1852 uint32_t LVN = VN.lookupOrAdd(LHS);
1853 if ((isa<Argument>(LHS) && isa<Argument>(RHS)) ||
1854 (isa<Instruction>(LHS) && isa<Instruction>(RHS))) {
1857 uint32_t RVN = VN.lookupOrAdd(RHS);
1873 if (RootDominatesEnd && !isa<Instruction>(RHS))
1874 addToLeaderTable(LVN, RHS, Root.
getEnd());
1880 unsigned NumReplacements =
1885 Changed |= NumReplacements > 0;
1886 NumGVNEqProp += NumReplacements;
1889 MD->invalidateCachedPointerInfo(LHS);
1905 bool isKnownFalse = !isKnownTrue;
1912 Worklist.
push_back(std::make_pair(A, RHS));
1913 Worklist.
push_back(std::make_pair(B, RHS));
1920 if (
CmpInst *Cmp = dyn_cast<CmpInst>(LHS)) {
1921 Value *Op0 = Cmp->getOperand(0), *Op1 = Cmp->getOperand(1);
1928 Worklist.
push_back(std::make_pair(Op0, Op1));
1936 uint32_t NextNum = VN.getNextUnusedValueNumber();
1937 uint32_t Num = VN.lookupOrAddCmp(Cmp->getOpcode(), NotPred, Op0, Op1);
1940 if (Num < NextNum) {
1942 if (NotCmp && isa<Instruction>(NotCmp)) {
1943 unsigned NumReplacements =
1948 Changed |= NumReplacements > 0;
1949 NumGVNEqProp += NumReplacements;
1952 MD->invalidateCachedPointerInfo(NotCmp);
1959 if (RootDominatesEnd)
1960 addToLeaderTable(Num, NotVal, Root.
getEnd());
1973 if (isa<DbgInfoIntrinsic>(I))
1982 bool Changed =
false;
1988 markInstructionForDeletion(I);
1992 if (MD && V->getType()->isPtrOrPtrVectorTy())
1993 MD->invalidateCachedPointerInfo(V);
2001 return processAssumeIntrinsic(IntrinsicI);
2003 if (
LoadInst *LI = dyn_cast<LoadInst>(I)) {
2004 if (processLoad(LI))
2007 unsigned Num = VN.lookupOrAdd(LI);
2008 addToLeaderTable(Num, LI, LI->
getParent());
2014 if (
BranchInst *BI = dyn_cast<BranchInst>(I)) {
2015 if (!BI->isConditional())
2018 if (isa<Constant>(BI->getCondition()))
2019 return processFoldableCondBr(BI);
2021 Value *BranchCond = BI->getCondition();
2025 if (TrueSucc == FalseSucc)
2029 bool Changed =
false;
2033 Changed |= propagateEquality(BranchCond, TrueVal, TrueE,
true);
2037 Changed |= propagateEquality(BranchCond, FalseVal, FalseE,
true);
2044 Value *SwitchCond =
SI->getCondition();
2046 bool Changed =
false;
2050 for (
unsigned i = 0, n =
SI->getNumSuccessors(); i != n; ++i)
2051 ++SwitchEdges[
SI->getSuccessor(i)];
2057 if (SwitchEdges.
lookup(Dst) == 1) {
2059 Changed |= propagateEquality(SwitchCond, i->getCaseValue(),
E,
true);
2070 uint32_t NextNum = VN.getNextUnusedValueNumber();
2071 unsigned Num = VN.lookupOrAdd(I);
2075 if (isa<AllocaInst>(I) || I->
isTerminator() || isa<PHINode>(
I)) {
2076 addToLeaderTable(Num, I, I->
getParent());
2083 if (Num >= NextNum) {
2084 addToLeaderTable(Num, I, I->
getParent());
2093 addToLeaderTable(Num, I, I->
getParent());
2095 }
else if (Repl == I) {
2104 MD->invalidateCachedPointerInfo(Repl);
2105 markInstructionForDeletion(I);
2118 VN.setAliasAnalysis(&RunAA);
2125 InvalidBlockRPONumbers =
true;
2127 bool Changed =
false;
2128 bool ShouldContinue =
true;
2140 Changed |= removedBlock;
2143 unsigned Iteration = 0;
2144 while (ShouldContinue) {
2146 ShouldContinue = iterateOnFunction(F);
2147 Changed |= ShouldContinue;
2154 assignValNumForDeadCode();
2155 bool PREChanged =
true;
2156 while (PREChanged) {
2157 PREChanged = performPRE(F);
2158 Changed |= PREChanged;
2167 cleanupGlobalSets();
2178 assert(InstrsToErase.empty() &&
2179 "We expect InstrsToErase to be empty across iterations");
2180 if (DeadBlocks.count(BB))
2184 ReplaceOperandsWithMap.clear();
2185 bool ChangedFunction =
false;
2189 if (!ReplaceOperandsWithMap.empty())
2190 ChangedFunction |= replaceOperandsForInBlockEquality(&*BI);
2191 ChangedFunction |= processInstruction(&*BI);
2193 if (InstrsToErase.empty()) {
2199 NumGVNInstr += InstrsToErase.size();
2202 bool AtStart = BI == BB->
begin();
2206 for (
auto *I : InstrsToErase) {
2207 assert(I->
getParent() == BB &&
"Removing instruction from wrong block?");
2210 if (MD) MD->removeInstruction(I);
2212 ICF->removeInstruction(I);
2215 InstrsToErase.
clear();
2223 return ChangedFunction;
2236 if (isa<Argument>(Op) || isa<Constant>(Op) || isa<GlobalValue>(Op))
2242 if (!VN.exists(Op)) {
2247 VN.phiTranslate(Pred, Curr, VN.lookup(Op), *
this);
2248 if (
Value *V = findLeader(Pred, TValNo)) {
2266 unsigned Num = VN.lookupOrAdd(Instr);
2270 addToLeaderTable(Num, Instr, Pred);
2274 bool GVN::performScalarPRE(
Instruction *CurInst) {
2275 if (isa<AllocaInst>(CurInst) || CurInst->
isTerminator() ||
2278 isa<DbgInfoIntrinsic>(CurInst))
2285 if (isa<CmpInst>(CurInst))
2295 if (isa<GetElementPtrInst>(CurInst))
2299 if (
auto *CallB = dyn_cast<CallBase>(CurInst))
2300 if (CallB->isInlineAsm())
2303 uint32_t ValNo = VN.lookup(CurInst);
2311 unsigned NumWith = 0;
2312 unsigned NumWithout = 0;
2317 if (InvalidBlockRPONumbers)
2318 assignBlockRPONumber(*CurrentBlock->
getParent());
2324 if (!DT->isReachableFromEntry(
P)) {
2331 assert(BlockRPONumber.count(
P) && BlockRPONumber.count(CurrentBlock) &&
2332 "Invalid BlockRPONumber map.");
2333 if (BlockRPONumber[
P] >= BlockRPONumber[CurrentBlock] &&
2335 if (
auto *Inst = dyn_cast<Instruction>(U.get()))
2336 return Inst->getParent() == CurrentBlock;
2343 uint32_t TValNo = VN.phiTranslate(
P, CurrentBlock, ValNo, *
this);
2344 Value *predV = findLeader(
P, TValNo);
2346 predMap.push_back(std::make_pair(static_cast<Value *>(
nullptr),
P));
2349 }
else if (predV == CurInst) {
2354 predMap.push_back(std::make_pair(predV,
P));
2361 if (NumWithout > 1 || NumWith == 0)
2369 if (NumWithout != 0) {
2375 if (ICF->isDominatedByICFIFromSameBlock(CurInst))
2393 toSplit.push_back(std::make_pair(PREPred->
getTerminator(), SuccNum));
2397 PREInstr = CurInst->
clone();
2398 if (!performScalarPREInsertion(PREInstr, PREPred, CurrentBlock, ValNo)) {
2408 assert(PREInstr !=
nullptr || NumWithout == 0);
2415 CurInst->
getName() +
".pre-phi", &CurrentBlock->
front());
2416 for (
unsigned i = 0,
e = predMap.size(); i !=
e; ++i) {
2429 VN.eraseTranslateCacheEntry(ValNo, *CurrentBlock);
2430 addToLeaderTable(ValNo, Phi, CurrentBlock);
2434 MD->invalidateCachedPointerInfo(Phi);
2436 removeFromLeaderTable(ValNo, CurInst, CurrentBlock);
2440 MD->removeInstruction(CurInst);
2444 ICF->removeInstruction(CurInst);
2453 bool GVN::performPRE(
Function &F) {
2454 bool Changed =
false;
2461 if (CurrentBlock->isEHPad())
2465 BE = CurrentBlock->end();
2468 Changed |= performScalarPRE(CurInst);
2472 if (splitCriticalEdges())
2484 MD->invalidateCachedPredecessors();
2485 InvalidBlockRPONumbers =
true;
2491 bool GVN::splitCriticalEdges() {
2492 if (toSplit.empty())
2495 std::pair<Instruction *, unsigned> Edge = toSplit.pop_back_val();
2498 }
while (!toSplit.empty());
2499 if (MD) MD->invalidateCachedPredecessors();
2500 InvalidBlockRPONumbers =
true;
2505 bool GVN::iterateOnFunction(
Function &F) {
2506 cleanupGlobalSets();
2509 bool Changed =
false;
2516 Changed |= processBlock(BB);
2521 void GVN::cleanupGlobalSets() {
2523 LeaderTable.clear();
2524 BlockRPONumber.clear();
2525 TableAllocator.Reset();
2527 InvalidBlockRPONumbers =
true;
2532 void GVN::verifyRemoved(
const Instruction *Inst)
const {
2533 VN.verifyRemoved(Inst);
2538 I = LeaderTable.begin(),
E = LeaderTable.end(); I !=
E; ++
I) {
2539 const LeaderTableEntry *Node = &I->second;
2540 assert(Node->Val != Inst &&
"Inst still in value numbering scope!");
2542 while (Node->Next) {
2544 assert(Node->Val != Inst &&
"Inst still in value numbering scope!");
2558 while (!NewDead.
empty()) {
2560 if (DeadBlocks.count(D))
2565 DT->getDescendants(D, Dom);
2571 if (DeadBlocks.count(S))
2574 bool AllPredDead =
true;
2576 if (!DeadBlocks.count(
P)) {
2577 AllPredDead =
false;
2600 if (DeadBlocks.count(B))
2607 if (!DeadBlocks.count(
P))
2614 DeadBlocks.insert(
P = S);
2620 if (!DeadBlocks.count(
P))
2625 MD->invalidateCachedPointerInfo(&Phi);
2644 bool GVN::processFoldableCondBr(
BranchInst *BI) {
2658 if (DeadBlocks.count(DeadRoot))
2662 DeadRoot = splitCriticalEdges(BI->
getParent(), DeadRoot);
2664 addDeadBlock(DeadRoot);
2672 void GVN::assignValNumForDeadCode() {
2675 unsigned ValNum = VN.lookupOrAdd(&Inst);
2676 addToLeaderTable(ValNum, &Inst, BB);
2686 :
FunctionPass(ID), NoMemDepAnalysis(NoMemDepAnalysis) {
2691 if (skipFunction(F))
2694 auto *LIWP = getAnalysisIfAvailable<LoopInfoWrapperPass>();
2696 return Impl.runImpl(
2697 F, getAnalysis<AssumptionCacheTracker>().getAssumptionCache(F),
2698 getAnalysis<DominatorTreeWrapperPass>().getDomTree(),
2699 getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(F),
2700 getAnalysis<AAResultsWrapperPass>().getAAResults(),
2703 : &getAnalysis<MemoryDependenceWrapperPass>().getMemDep(),
2704 LIWP ? &LIWP->getLoopInfo() :
nullptr,
2705 &getAnalysis<OptimizationRemarkEmitterWrapperPass>().getORE());
2713 if (!NoMemDepAnalysis)
2726 bool NoMemDepAnalysis;
Legacy wrapper pass to provide the GlobalsAAResult object.
static AvailableValueInBlock get(BasicBlock *BB, AvailableValue &&AV)
BinaryOp_match< LHS, RHS, Instruction::And > m_And(const LHS &L, const RHS &R)
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static cl::opt< bool > EnableLoadPRE("enable-load-pre", cl::init(true))
void eraseTranslateCacheEntry(uint32_t Num, const BasicBlock &CurrBlock)
Erase stale entry from phiTranslate cache so phiTranslate can be computed again.
A parsed version of the target data layout string in and methods for querying it. ...
bool isUndefValue() const
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
This class is the base class for the comparison instructions.
static bool runImpl(Function &F, TargetLibraryInfo &TLI, DominatorTree &DT)
This is the entry point for all transforms.
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
Helper class for SSA formation on a set of values defined in multiple blocks.
Provides a lazy, caching interface for making common memory aliasing information queries, backed by LLVM's alias analysis passes.
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...
DILocation * get() const
Get the underlying DILocation.
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
static AvailableValue getMI(MemIntrinsic *MI, unsigned Offset=0)
unsigned Offset
Offset - The byte offset in Val that is interesting for the load query.
DiagnosticInfoOptimizationBase::Argument NV
static Type * makeCmpResultType(Type *opnd_type)
Create a result type for fcmp/icmp.
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This class represents lattice values for constants.
PointerTy getPointer() const
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
bool isAtomic() const
Return true if this instruction has an AtomicOrdering of unordered or higher.
This is the interface for a simple mod/ref and alias analysis over globals.
void Initialize(Type *Ty, StringRef Name)
Reset this object to get ready for a new set of SSA updates with type 'Ty'.
Represents an op.with.overflow intrinsic.
uint32_t lookupOrAddCmp(unsigned Opcode, CmpInst::Predicate Pred, Value *LHS, Value *RHS)
Returns the value number of the given comparison, assigning it a new number if it did not have one be...
void push_back(const T &Elt)
void AddAvailableValue(BasicBlock *BB, Value *V)
Indicate that a rewritten value is available in the specified block with the specified value...
bool operator==(const Expression &other) const
static bool lookup(const GsymReader &GR, DataExtractor &Data, uint64_t &Offset, uint64_t BaseAddr, uint64_t Addr, SourceLocations &SrcLocs, llvm::Error &Err)
A Lookup helper functions.
This class represents a function call, abstracting a target machine's calling convention.
bool isNonLocal() const
Tests if this MemDepResult represents a query that is transparent to the start of the block...
An immutable pass that tracks lazily created AssumptionCache objects.
A cache of @llvm.assume calls within a function.
bool salvageDebugInfo(Instruction &I)
Assuming the instruction I is going to be deleted, attempt to salvage debug users of I by writing the...
AtomicOrdering getOrdering() const
Returns the ordering constraint of this load instruction.
uint32_t phiTranslate(const BasicBlock *BB, const BasicBlock *PhiBlock, uint32_t Num, GVN &Gvn)
Wrap phiTranslateImpl to provide caching functionality.
bool isTerminator() const
void deleteValue()
Delete a pointer to a generic Value.
bool hasFnAttribute(Attribute::AttrKind Kind) const
Return true if the function has the attribute.
This class implements a map that also provides access to all stored values in a deterministic order...
BasicBlock * getSuccessor(unsigned i) const
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
STATISTIC(NumFunctions, "Total number of functions")
Analysis pass which computes a DominatorTree.
bool isCoercedLoadValue() const
An instruction for reading from memory.
const BasicBlock * getEnd() const
Value * getCondition() const
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.
static bool impliesEquivalanceIfTrue(CmpInst *Cmp)
unsigned replaceDominatedUsesWith(Value *From, Value *To, DominatorTree &DT, const BasicBlockEdge &Edge)
Replace each use of 'From' with 'To' if that use is dominated by the given edge.
iterator end()
Get an iterator to the end of the SetVector.
Value * getMemInstValueForLoad(MemIntrinsic *SrcInst, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingMemInst returned an offset, this function can be used to actually perform...
LLVMContext & getContext() const
Get the context in which this basic block lives.
gvn Early GVN Hoisting of Expressions
static Constant * getNullValue(Type *Ty)
Constructor to create a '0' constant of arbitrary type.
iterator begin()
Instruction iterator methods.
uint32_t lookup(Value *V, bool Verify=true) const
Returns the value number of the specified value.
bool MergeBlockIntoPredecessor(BasicBlock *BB, DomTreeUpdater *DTU=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, MemoryDependenceResults *MemDep=nullptr, bool PredecessorWithTwoSuccessors=false)
Attempts to merge a block into its predecessor, if possible.
Value * getArgOperand(unsigned i) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
void dump() const
Support for debugging, callable in GDB: V->dump()
bool match(Val *V, const Pattern &P)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isVolatile() const
Return true if this is a load from a volatile memory location.
void getAnalysisUsage(AnalysisUsage &AU) const override
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static cl::opt< bool > EnablePRE("enable-pre", cl::init(true), cl::Hidden)
void patchReplacementInstruction(Instruction *I, Value *Repl)
Patch the replacement so that it is not more restrictive than the value being replaced.
bool isDef() const
Tests if this MemDepResult represents a query that is an instruction definition dependency.
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
bool runOnFunction(Function &F) override
runOnFunction - Virtual method overriden by subclasses to do the per-function processing of the pass...
Option class for critical edge splitting.
void clear()
Remove all entries from the ValueTable.
bool isClobber() const
Tests if this MemDepResult represents a query that is an instruction clobber dependency.
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.
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...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
MemoryDependenceResults & getMemDep() const
bool isIntegerTy() const
True if this is an instance of IntegerType.
This file contains the simple types necessary to represent the attributes associated with functions a...
An analysis that produces MemoryDependenceResults for a function.
void setName(const Twine &Name)
Change the name of the value.
Analysis pass that exposes the LoopInfo for a function.
bool isSimpleValue() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
FastMathFlags getFastMathFlags() const
Convenience function for getting all the fast-math flags, which must be an operator which supports th...
Type * getType() const
All values are typed, get the type of this value.
ppc ctr loops PowerPC CTR Loops Verify
bool insert(const value_type &X)
Insert a new element into the SetVector.
The core GVN pass object.
bool canCoerceMustAliasedValueToLoad(Value *StoredVal, Type *LoadTy, const DataLayout &DL)
Return true if CoerceAvailableValueToLoadType would succeed if it was called.
Expression(uint32_t o=~2U)
iterator begin()
Get an iterator to the beginning of the SetVector.
MDNode * getMetadata(unsigned KindID) const
Get the metadata of given kind attached to this Instruction.
DiagnosticInfoOptimizationBase::setExtraArgs setExtraArgs
static AvailableValue getLoad(LoadInst *LI, unsigned Offset=0)
hash_code hash_value(const APFloat &Arg)
See friend declarations above.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
AnalysisUsage & addPreservedID(const void *ID)
LoadInst * getCoercedLoadValue() const
static GVN::Expression getEmptyKey()
An instruction for storing to memory.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
void add(Value *V, uint32_t num)
add - Insert a value into the table with a specified value number.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void takeName(Value *V)
Transfer the name from V to this value.
static unsigned getHashValue(const GVN::Expression &e)
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
Value * getOperand(unsigned i) const
Interval::succ_iterator succ_end(Interval *I)
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 initializeGVNLegacyPassPass(PassRegistry &)
bool isVoidTy() const
Return true if this is 'void'.
const BasicBlock & getEntryBlock() const
an instruction for type-safe pointer arithmetic to access elements of arrays and structs ...
void getAAMetadata(AAMDNodes &N, bool Merge=false) const
Fills the AAMDNodes structure with AA metadata from this instruction.
initializer< Ty > init(const Ty &Val)
Value * GetValueInMiddleOfBlock(BasicBlock *BB)
Construct SSA form, materializing a value that is live in the middle of the specified block...
SmallVector< uint32_t, 4 > varargs
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
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.
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
const BasicBlock * getSinglePredecessor() const
Return the predecessor of this block if it has a single predecessor block.
void insertBefore(Instruction *InsertPos)
Insert an unlinked instruction into a basic block immediately before the specified instruction...
LLVM Basic Block Representation.
PointerIntPair - This class implements a pair of a pointer and small integer.
PHITransAddr - An address value which tracks and handles phi translation.
The instances of the Type class are immutable: once they are created, they are never changed...
BinaryOp_match< LHS, RHS, Instruction::Or > m_Or(const LHS &L, const RHS &R)
This class holds the mapping between values and value numbers.
Conditional or Unconditional Branch instruction.
This file provides the interface for LLVM's Global Value Numbering pass which eliminates fully redund...
static GVN::Expression getTombstoneKey()
static Value * ConstructSSAForLoadSet(LoadInst *LI, SmallVectorImpl< AvailableValueInBlock > &ValuesPerBlock, GVN &gvn)
Given a set of loads specified by ValuesPerBlock, construct SSA form, allowing us to eliminate LI...
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
static bool isEqual(const GVN::Expression &LHS, const GVN::Expression &RHS)
This file contains the declarations for the subclasses of Constant, which represent the different fla...
static cl::opt< uint32_t > MaxRecurseDepth("gvn-max-recurse-depth", cl::Hidden, cl::init(1000), cl::ZeroOrMore, cl::desc("Max recurse depth in GVN (default = 1000)"))
const Instruction & front() const
A manager for alias analyses.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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...
Represent the analysis usage information of a pass.
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.
PointerIntPair< Value *, 2, ValType > Val
V - The value that is live out of the block.
MemIntrinsic * getMemIntrinValue() const
FunctionPass class - This class is used to implement most global optimizations.
amdgpu Simplify well known AMD library false FunctionCallee Value * Arg
Interval::pred_iterator pred_end(Interval *I)
Value * getPointerOperand()
bool isCriticalEdge(const Instruction *TI, unsigned SuccNum, bool AllowIdenticalEdges=false)
Return true if the specified edge is a critical edge.
Value * getLoadValueForLoad(LoadInst *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingLoad returned an offset, this function can be used to actually perform th...
static void reportLoadElim(LoadInst *LI, Value *AvailableValue, OptimizationRemarkEmitter *ORE)
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 cl::opt< bool > EnableMemDep("enable-gvn-memdep", cl::init(true))
A wrapper analysis pass for the legacy pass manager that exposes a MemoryDepnedenceResults instance...
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
A memory dependence query can return one of three different answers.
static RegisterPass< DebugifyFunctionPass > DF("debugify-function", "Attach debug info to a function")
DominatorTree & getDominatorTree() const
static cl::opt< uint32_t > MaxNumDeps("gvn-max-num-deps", cl::Hidden, cl::init(100), cl::ZeroOrMore, cl::desc("Max number of dependences to attempt Load PRE (default = 100)"))
Intrinsic::ID getIntrinsicID() const
Return the intrinsic ID of this intrinsic.
static void reportMayClobberedLoad(LoadInst *LI, MemDepResult DepInfo, DominatorTree *DT, OptimizationRemarkEmitter *ORE)
Try to locate the three instruction involved in a missed load-elimination case that is due to an inte...
A function analysis which provides an AssumptionCache.
bool isPtrOrPtrVectorTy() const
Return true if this is a pointer type or a vector of pointer types.
Value * MaterializeAdjustedValue(LoadInst *LI, GVN &gvn) const
Emit code at the end of this block to adjust the value defined here to the specified type...
A SetVector that performs no allocations if smaller than a certain size.
This is the common base class for memset/memcpy/memmove.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Value * PHITranslateWithInsertion(BasicBlock *CurBB, BasicBlock *PredBB, const DominatorTree &DT, SmallVectorImpl< Instruction *> &NewInsts)
PHITranslateWithInsertion - PHI translate this value into the specified predecessor block...
This is the shared class of boolean and integer constants.
This struct is a compact representation of a valid (power of two) or undefined (0) alignment...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
const MemDepResult & getResult() const
size_type count(const KeyT &Key) const
BasicBlock * getBB() const
#define INITIALIZE_PASS_BEGIN(passName, arg, name, cfg, analysis)
A collection of metadata nodes that might be associated with a memory access used by the alias-analys...
LLVM_NODISCARD T pop_back_val()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
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...
pred_range predecessors(BasicBlock *BB)
Value * MaterializeAdjustedValue(LoadInst *LI, Instruction *InsertPt, GVN &gvn) const
Emit code at the specified insertion point to adjust the value defined here to the specified type...
static ConstantInt * getTrue(LLVMContext &Context)
bool isCommutative() const
Return true if the instruction is commutative:
void setOperand(unsigned i, Value *Val)
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 Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
hash_code hash_combine(const Ts &...args)
Combine values into a single hash_code.
Represents an AvailableValue which can be rematerialized at the end of the associated BasicBlock...
iterator_range< user_iterator > users()
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
std::vector< NonLocalDepEntry > NonLocalDepInfo
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 ...
iterator insert(iterator I, T &&Elt)
void verifyRemoved(const Value *) const
verifyRemoved - Verify that the value is removed from all internal data structures.
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
void erase(Value *v)
Remove a value from the value numbering.
static bool isLifetimeStart(const Instruction *Inst)
Predicate getPredicate() const
Return the predicate for this instruction.
static bool isZero(Value *V, const DataLayout &DL, DominatorTree *DT, AssumptionCache *AC)
unsigned GetSuccessorNumber(const BasicBlock *BB, const BasicBlock *Succ)
Search for the specified successor of basic block BB and return its position in the terminator instru...
unsigned getNumArgOperands() const
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
unsigned getAlignment() const
Return the alignment of the access that is being performed.
Instruction * getInst() const
If this is a normal dependency, returns the instruction that is depended on.
Value * getStoreValueForLoad(Value *SrcVal, unsigned Offset, Type *LoadTy, Instruction *InsertPt, const DataLayout &DL)
If analyzeLoadFromClobberingStore returned an offset, this function can be used to actually perform t...
LLVM_NODISCARD bool empty() const
GVNLegacyPass(bool NoMemDepAnalysis=!EnableMemDep)
StringRef getName() const
Return a constant reference to the value's name.
const Function * getParent() const
Return the enclosing method, or null if none.
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...
SyncScope::ID getSyncScopeID() const
Returns the synchronization scope ID of this load instruction.
bool mayReadFromMemory() const
Return true if this instruction may read memory.
static AvailableValue get(Value *V, unsigned Offset=0)
PassT::Result * getCachedResult(IRUnitT &IR) const
Get the cached result of an analysis pass for a given IR unit.
bool exists(Value *V) const
Returns true if a value number exists for the specified value.
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< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
This class allows to keep track on instructions with implicit control flow.
bool isUnconditional() const
friend hash_code hash_value(const Expression &Value)
uint32_t lookupOrAdd(Value *V)
lookup_or_add - Returns the value number for the specified value, assigning it a new number if it did...
ValueT lookup(const_arg_type_t< KeyT > Val) const
lookup - Return the entry for the specified key, or a default constructed value if no such entry exis...
static bool impliesEquivalanceIfFalse(CmpInst *Cmp)
Value * getSimpleValue() const
ValueTable & operator=(const ValueTable &Arg)
Analysis pass providing the TargetLibraryInfo.
iterator_range< df_iterator< T > > depth_first(const T &G)
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
const BasicBlock * getStart() const
Represents a particular available value that we know how to materialize.
bool isSafeToSpeculativelyExecute(const Value *V, const Instruction *CtxI=nullptr, const DominatorTree *DT=nullptr)
Return true if the instruction does not have any effects besides calculating the result and does not ...
static bool IsValueFullyAvailableInBlock(BasicBlock *BB, DenseMap< BasicBlock *, char > &FullyAvailableBlocks, uint32_t RecurseDepth)
Return true if we can prove that the value we're analyzing is fully available in the specified block...
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.
static AvailableValueInBlock getUndef(BasicBlock *BB)
void removeInstruction(Instruction *InstToRemove)
Removes an instruction from the dependence analysis, updating the dependence of instructions that pre...
succ_range successors(Instruction *I)
static const Function * getParent(const Value *V)
The legacy pass manager's analysis pass to compute loop information.
PreservedAnalyses run(Function &F, FunctionAnalysisManager &AM)
Run the pass over the function.
bool hasOneUse() const
Return true if there is exactly one user of this value.
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
This is an entry in the NonLocalDepInfo cache.
A container for analyses that lazily runs them and caches their results.
BasicBlock * BB
BB - The basic block in question.
static void patchAndReplaceAllUsesWith(Instruction *I, Value *Repl)
Legacy analysis pass which computes a DominatorTree.
bool isMemIntrinValue() const
A wrapper pass to provide the legacy pass manager access to a suitably prepared AAResults object...
This header defines various interfaces for pass management in LLVM.
AvailableValue AV
AV - The actual available value.
Value * SimplifyInstruction(Instruction *I, const SimplifyQuery &Q, OptimizationRemarkEmitter *ORE=nullptr)
See if we can compute a simplified version of this instruction.
static IntegerType * getInt8Ty(LLVMContext &C)
static bool hasUsersIn(Value *V, BasicBlock *BB)
FunctionPass * createGVNPass(bool NoMemDepAnalysis=false)
Create a legacy GVN pass.
static AvailableValue getUndef()
static bool isOnlyReachableViaThisEdge(const BasicBlockEdge &E, DominatorTree *DT)
There is an edge from 'Src' to 'Dst'.
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
This instruction inserts a struct field of array element value into an aggregate value.
bool HasValueForBlock(BasicBlock *BB) const
Return true if the SSAUpdater already has a value for the specified block.