79 #include "llvm/Config/llvm-config.h" 122 using namespace llvm;
124 #define DEBUG_TYPE "loop-reduce" 138 cl::desc(
"Enable LSR phi elimination"));
143 cl::desc(
"Add instruction count to a LSR cost model"));
148 cl::desc(
"Narrow LSR complex solution using" 149 " expectation of registers number"));
155 cl::desc(
"Narrow LSR search space by filtering non-optimal formulae" 156 " with the same ScaledReg and Scale"));
162 cl::desc(
"Stress test LSR IV chains"));
174 Type *MemTy =
nullptr;
177 MemAccessTy() =
default;
178 MemAccessTy(
Type *Ty,
unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
181 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
184 bool operator!=(MemAccessTy Other)
const {
return !(*
this == Other); }
187 unsigned AS = UnknownAddressSpace) {
207 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 209 OS <<
"[NumUses=" << UsedByIndices.count() <<
']';
220 class RegUseTracker {
223 RegUsesTy RegUsesMap;
227 void countRegister(
const SCEV *
Reg,
size_t LUIdx);
228 void dropRegister(
const SCEV *
Reg,
size_t LUIdx);
229 void swapAndDropUse(
size_t LUIdx,
size_t LastLUIdx);
231 bool isRegUsedByUsesOtherThan(
const SCEV *
Reg,
size_t LUIdx)
const;
240 iterator
begin() {
return RegSequence.
begin(); }
241 iterator
end() {
return RegSequence.
end(); }
242 const_iterator
begin()
const {
return RegSequence.
begin(); }
243 const_iterator
end()
const {
return RegSequence.
end(); }
249 RegUseTracker::countRegister(
const SCEV *
Reg,
size_t LUIdx) {
250 std::pair<RegUsesTy::iterator, bool> Pair =
251 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
252 RegSortData &RSD = Pair.first->second;
255 RSD.UsedByIndices.resize(
std::max(RSD.UsedByIndices.size(), LUIdx + 1));
256 RSD.UsedByIndices.set(LUIdx);
260 RegUseTracker::dropRegister(
const SCEV *Reg,
size_t LUIdx) {
261 RegUsesTy::iterator It = RegUsesMap.find(Reg);
262 assert(It != RegUsesMap.end());
263 RegSortData &RSD = It->second;
264 assert(RSD.UsedByIndices.size() > LUIdx);
265 RSD.UsedByIndices.reset(LUIdx);
269 RegUseTracker::swapAndDropUse(
size_t LUIdx,
size_t LastLUIdx) {
270 assert(LUIdx <= LastLUIdx);
274 for (
auto &Pair : RegUsesMap) {
276 if (LUIdx < UsedByIndices.
size())
277 UsedByIndices[LUIdx] =
278 LastLUIdx < UsedByIndices.
size() ? UsedByIndices[LastLUIdx] :
false;
279 UsedByIndices.
resize(std::min(UsedByIndices.
size(), LastLUIdx));
284 RegUseTracker::isRegUsedByUsesOtherThan(
const SCEV *Reg,
size_t LUIdx)
const {
285 RegUsesTy::const_iterator
I = RegUsesMap.find(Reg);
286 if (I == RegUsesMap.end())
290 if (i == -1)
return false;
291 if ((
size_t)i != LUIdx)
return true;
296 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
297 assert(I != RegUsesMap.end() &&
"Unknown register!");
298 return I->second.UsedByIndices;
315 int64_t BaseOffset = 0;
318 bool HasBaseReg =
false;
341 const SCEV *ScaledReg =
nullptr;
346 int64_t UnfoldedOffset = 0;
354 void canonicalize(
const Loop &L);
358 bool hasZeroEnd()
const;
360 size_t getNumRegs()
const;
363 void deleteBaseReg(
const SCEV *&S);
365 bool referencesReg(
const SCEV *S)
const;
366 bool hasRegsUsedByUsesOtherThan(
size_t LUIdx,
367 const RegUseTracker &RegUses)
const;
388 for (
const SCEV *S :
Add->operands())
395 if (!AR->getStart()->isZero() && AR->isAffine()) {
398 AR->getStepRecurrence(SE),
406 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
407 if (Mul->getOperand(0)->isAllOnesValue()) {
416 for (
const SCEV *S : MyGood)
418 for (
const SCEV *S : MyBad)
437 BaseRegs.push_back(Sum);
443 BaseRegs.push_back(Sum);
454 return BaseRegs.size() <= 1;
459 if (Scale == 1 && BaseRegs.empty())
463 if (SAR && SAR->
getLoop() == &L)
471 return isa<const SCEVAddRecExpr>(S) &&
472 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
474 return I == BaseRegs.end();
483 void Formula::canonicalize(
const Loop &L) {
488 assert(!BaseRegs.empty() &&
"1*reg => reg, should not be needed.");
492 ScaledReg = BaseRegs.back();
501 if (!SAR || SAR->
getLoop() != &L) {
504 return isa<const SCEVAddRecExpr>(S) &&
505 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
507 if (I != BaseRegs.end())
516 bool Formula::unscale() {
520 BaseRegs.push_back(ScaledReg);
525 bool Formula::hasZeroEnd()
const {
526 if (UnfoldedOffset || BaseOffset)
528 if (BaseRegs.size() != 1 || ScaledReg)
535 size_t Formula::getNumRegs()
const {
536 return !!ScaledReg + BaseRegs.size();
542 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
543 ScaledReg ? ScaledReg->getType() :
544 BaseGV ? BaseGV->getType() :
549 void Formula::deleteBaseReg(
const SCEV *&S) {
550 if (&S != &BaseRegs.back())
556 bool Formula::referencesReg(
const SCEV *S)
const {
562 bool Formula::hasRegsUsedByUsesOtherThan(
size_t LUIdx,
563 const RegUseTracker &RegUses)
const {
565 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
567 for (
const SCEV *BaseReg : BaseRegs)
568 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
573 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 577 if (!First) OS <<
" + ";
else First =
false;
578 BaseGV->printAsOperand(OS,
false);
580 if (BaseOffset != 0) {
581 if (!First) OS <<
" + ";
else First =
false;
584 for (
const SCEV *BaseReg : BaseRegs) {
585 if (!First) OS <<
" + ";
else First =
false;
586 OS <<
"reg(" << *BaseReg <<
')';
588 if (HasBaseReg && BaseRegs.empty()) {
589 if (!First) OS <<
" + ";
else First =
false;
590 OS <<
"**error: HasBaseReg**";
591 }
else if (!HasBaseReg && !BaseRegs.empty()) {
592 if (!First) OS <<
" + ";
else First =
false;
593 OS <<
"**error: !HasBaseReg**";
596 if (!First) OS <<
" + ";
else First =
false;
597 OS << Scale <<
"*reg(";
604 if (UnfoldedOffset != 0) {
605 if (!First) OS <<
" + ";
606 OS <<
"imm(" << UnfoldedOffset <<
')';
647 bool IgnoreSignificantBits =
false) {
669 const APInt &LA =
C->getAPInt();
671 if (LA.
srem(RA) != 0)
678 if ((IgnoreSignificantBits ||
isAddRecSExtable(AR, SE)) && AR->isAffine()) {
680 IgnoreSignificantBits);
681 if (!Step)
return nullptr;
683 IgnoreSignificantBits);
684 if (!Start)
return nullptr;
697 for (
const SCEV *S :
Add->operands()) {
699 if (!Op)
return nullptr;
708 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
712 for (
const SCEV *S : Mul->operands()) {
715 IgnoreSignificantBits)) {
734 if (
C->getAPInt().getMinSignedBits() <= 64) {
736 return C->getValue()->getSExtValue();
744 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
759 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
760 if (
GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
770 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
786 bool isAddress = isa<LoadInst>(Inst);
788 if (
SI->getPointerOperand() == OperandVal)
790 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
793 switch (II->getIntrinsicID()) {
794 case Intrinsic::memset:
796 if (II->getArgOperand(0) == OperandVal)
799 case Intrinsic::memmove:
800 case Intrinsic::memcpy:
801 if (II->getArgOperand(0) == OperandVal ||
802 II->getArgOperand(1) == OperandVal)
808 if (IntrInfo.
PtrVal == OperandVal)
813 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
814 if (RMW->getPointerOperand() == OperandVal)
817 if (CmpX->getPointerOperand() == OperandVal)
827 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
828 AccessTy.MemTy =
SI->getOperand(0)->getType();
829 AccessTy.AddrSpace =
SI->getPointerAddressSpace();
830 }
else if (
const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
831 AccessTy.AddrSpace = LI->getPointerAddressSpace();
832 }
else if (
const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
833 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
835 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
836 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
837 switch (II->getIntrinsicID()) {
839 case Intrinsic::memset:
840 AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
841 AccessTy.MemTy = OperandVal->
getType();
843 case Intrinsic::memmove:
844 case Intrinsic::memcpy:
846 AccessTy.MemTy = OperandVal->
getType();
862 if (
PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
864 PTy->getAddressSpace());
909 if (!Processed.
insert(S).second)
913 for (
const SCEV *S :
Add->operands()) {
920 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
921 if (Mul->getNumOperands() == 2) {
923 if (isa<SCEVConstant>(Mul->getOperand(0)))
928 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
929 Value *UVal = U->getValue();
933 if (UI && UI->
getOpcode() == Instruction::Mul &&
955 bool Changed =
false;
957 while (!DeadInsts.
empty()) {
994 const LSRUse &LU,
const Formula &
F);
998 const LSRUse &LU,
const Formula &F,
1034 assert(isValid() &&
"invalid cost");
1051 void RateRegister(
const SCEV *Reg,
1056 void RatePrimaryRegister(
const SCEV *Reg,
1072 Value *OperandValToReplace =
nullptr;
1084 LSRFixup() =
default;
1086 bool isUseFullyOutsideLoop(
const Loop *L)
const;
1094 struct UniquifierDenseMapInfo {
1097 V.
push_back(reinterpret_cast<const SCEV *>(-1));
1103 V.
push_back(reinterpret_cast<const SCEV *>(-2));
1139 MemAccessTy AccessTy;
1146 int64_t MaxOffset = std::numeric_limits<int64_t>::min();
1150 bool AllFixupsOutsideLoop =
true;
1157 bool RigidFormula =
false;
1163 Type *WidestFixupType =
nullptr;
1173 LSRUse(KindType K, MemAccessTy AT) :
Kind(K), AccessTy(AT) {}
1175 LSRFixup &getNewFixup() {
1177 return Fixups.
back();
1180 void pushFixup(LSRFixup &f) {
1182 if (f.Offset > MaxOffset)
1183 MaxOffset = f.Offset;
1184 if (f.Offset < MinOffset)
1185 MinOffset = f.Offset;
1188 bool HasFormulaWithSameRegs(
const Formula &F)
const;
1189 float getNotSelectedProbability(
const SCEV *Reg)
const;
1190 bool InsertFormula(
const Formula &F,
const Loop &L);
1191 void DeleteFormula(Formula &F);
1192 void RecomputeRegs(
size_t LUIdx, RegUseTracker &Reguses);
1201 LSRUse::KindType
Kind, MemAccessTy AccessTy,
1203 bool HasBaseReg, int64_t Scale,
1207 void Cost::RateRegister(
const SCEV *Reg,
1216 if (AR->getLoop() != L) {
1223 if (!AR->getLoop()->contains(L)) {
1233 unsigned LoopCost = 1;
1235 const SCEV *LoopStep = AR->getStepRecurrence(SE);
1236 if (isa<SCEVConstant>(LoopStep)) {
1240 const SCEV *LoopStart = AR->getStart();
1241 if (!isa<SCEVConstant>(LoopStart) &&
1247 C.AddRecCost += LoopCost;
1251 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1252 if (!Regs.
count(AR->getOperand(1))) {
1253 RateRegister(AR->getOperand(1),
Regs, L, SE, DT, TTI);
1263 if (!isa<SCEVUnknown>(Reg) &&
1264 !isa<SCEVConstant>(
Reg) &&
1265 !(isa<SCEVAddRecExpr>(Reg) &&
1266 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(
Reg)->getStart()) ||
1267 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
1270 C.NumIVMuls += isa<SCEVMulExpr>(
Reg) &&
1277 void Cost::RatePrimaryRegister(
const SCEV *Reg,
1283 if (LoserRegs && LoserRegs->
count(Reg)) {
1287 if (Regs.
insert(Reg).second) {
1288 RateRegister(Reg, Regs, L, SE, DT, TTI);
1289 if (LoserRegs && isLoser())
1302 assert(F.isCanonical(*L) &&
"Cost is accurate only for canonical formula");
1304 unsigned PrevAddRecCost =
C.AddRecCost;
1305 unsigned PrevNumRegs =
C.NumRegs;
1306 unsigned PrevNumBaseAdds =
C.NumBaseAdds;
1307 if (
const SCEV *ScaledReg = F.ScaledReg) {
1308 if (VisitedRegs.
count(ScaledReg)) {
1312 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs, TTI);
1316 for (
const SCEV *BaseReg : F.BaseRegs) {
1317 if (VisitedRegs.
count(BaseReg)) {
1321 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs, TTI);
1327 size_t NumBaseParts = F.getNumRegs();
1328 if (NumBaseParts > 1)
1333 C.NumBaseAdds += (F.UnfoldedOffset != 0);
1339 for (
const LSRFixup &
Fixup : LU.Fixups) {
1340 int64_t
O = Fixup.Offset;
1341 int64_t
Offset = (uint64_t)O + F.BaseOffset;
1345 else if (Offset != 0)
1352 Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
1358 assert(isValid() &&
"invalid cost");
1365 if (
C.NumRegs > TTIRegNum) {
1368 if (PrevNumRegs > TTIRegNum)
1369 C.Insns += (
C.NumRegs - PrevNumRegs);
1371 C.Insns += (
C.NumRegs - TTIRegNum);
1384 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() && !TTI.
canMacroFuseCmp())
1387 C.Insns += (
C.AddRecCost - PrevAddRecCost);
1390 if (LU.Kind != LSRUse::ICmpZero)
1391 C.Insns +=
C.NumBaseAdds - PrevNumBaseAdds;
1392 assert(isValid() &&
"invalid cost");
1410 C.Insns != Other.C.Insns)
1411 return C.Insns < Other.C.Insns;
1415 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1418 OS <<
C.Insns <<
" instruction" << (
C.Insns == 1 ?
" " :
"s ");
1419 OS <<
C.NumRegs <<
" reg" << (
C.NumRegs == 1 ?
"" :
"s");
1420 if (
C.AddRecCost != 0)
1421 OS <<
", with addrec cost " <<
C.AddRecCost;
1422 if (
C.NumIVMuls != 0)
1423 OS <<
", plus " <<
C.NumIVMuls <<
" IV mul" 1424 << (
C.NumIVMuls == 1 ?
"" :
"s");
1425 if (
C.NumBaseAdds != 0)
1426 OS <<
", plus " <<
C.NumBaseAdds <<
" base add" 1427 << (
C.NumBaseAdds == 1 ?
"" :
"s");
1428 if (
C.ScaleCost != 0)
1429 OS <<
", plus " <<
C.ScaleCost <<
" scale cost";
1431 OS <<
", plus " <<
C.ImmCost <<
" imm cost";
1432 if (
C.SetupCost != 0)
1433 OS <<
", plus " <<
C.SetupCost <<
" setup cost";
1442 bool LSRFixup::isUseFullyOutsideLoop(
const Loop *L)
const {
1444 if (
const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1445 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1446 if (PN->getIncomingValue(i) == OperandValToReplace &&
1447 L->
contains(PN->getIncomingBlock(i)))
1455 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1461 Store->getOperand(0)->printAsOperand(OS,
false);
1462 }
else if (UserInst->getType()->isVoidTy())
1463 OS << UserInst->getOpcodeName();
1465 UserInst->printAsOperand(OS,
false);
1467 OS <<
", OperandValToReplace=";
1468 OperandValToReplace->printAsOperand(OS,
false);
1470 for (
const Loop *PIL : PostIncLoops) {
1471 OS <<
", PostIncLoop=";
1472 PIL->getHeader()->printAsOperand(OS,
false);
1476 OS <<
", Offset=" <<
Offset;
1486 bool LSRUse::HasFormulaWithSameRegs(
const Formula &F)
const {
1488 if (F.ScaledReg) Key.
push_back(F.ScaledReg);
1491 return Uniquifier.count(Key);
1495 float LSRUse::getNotSelectedProbability(
const SCEV *Reg)
const {
1497 for (
const Formula &F : Formulae)
1498 if (F.referencesReg(Reg))
1500 return ((
float)(Formulae.size() - FNum)) / Formulae.size();
1505 bool LSRUse::InsertFormula(
const Formula &F,
const Loop &L) {
1506 assert(F.isCanonical(L) &&
"Invalid canonical representation");
1508 if (!Formulae.empty() && RigidFormula)
1512 if (F.ScaledReg) Key.
push_back(F.ScaledReg);
1516 if (!Uniquifier.insert(Key).second)
1520 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1521 "Zero allocated in a scaled register!");
1523 for (
const SCEV *BaseReg : F.BaseRegs)
1524 assert(!BaseReg->
isZero() &&
"Zero allocated in a base register!");
1528 Formulae.push_back(F);
1531 Regs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
1533 Regs.
insert(F.ScaledReg);
1539 void LSRUse::DeleteFormula(Formula &F) {
1540 if (&F != &Formulae.back())
1542 Formulae.pop_back();
1546 void LSRUse::RecomputeRegs(
size_t LUIdx, RegUseTracker &RegUses) {
1550 for (
const Formula &F : Formulae) {
1551 if (F.ScaledReg) Regs.
insert(F.ScaledReg);
1552 Regs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
1556 for (
const SCEV *S : OldRegs)
1558 RegUses.dropRegister(S, LUIdx);
1561 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1563 OS <<
"LSR Use: Kind=";
1565 case Basic: OS <<
"Basic";
break;
1566 case Special: OS <<
"Special";
break;
1567 case ICmpZero: OS <<
"ICmpZero";
break;
1569 OS <<
"Address of ";
1570 if (AccessTy.MemTy->isPointerTy())
1573 OS << *AccessTy.MemTy;
1576 OS <<
" in addrspace(" << AccessTy.AddrSpace <<
')';
1579 OS <<
", Offsets={";
1580 bool NeedComma =
false;
1582 if (NeedComma) OS <<
',';
1588 if (AllFixupsOutsideLoop)
1589 OS <<
", all-fixups-outside-loop";
1591 if (WidestFixupType)
1592 OS <<
", widest fixup type: " << *WidestFixupType;
1601 LSRUse::KindType Kind, MemAccessTy AccessTy,
1603 bool HasBaseReg, int64_t Scale,
1608 HasBaseReg, Scale, AccessTy.AddrSpace, Fixup);
1610 case LSRUse::ICmpZero:
1617 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1622 if (Scale != 0 && Scale != -1)
1627 if (BaseOffset != 0) {
1635 BaseOffset = -(uint64_t)BaseOffset;
1644 return !BaseGV && Scale == 0 && BaseOffset == 0;
1646 case LSRUse::Special:
1648 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1655 int64_t MinOffset, int64_t MaxOffset,
1656 LSRUse::KindType Kind, MemAccessTy AccessTy,
1658 bool HasBaseReg, int64_t Scale) {
1660 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1663 MinOffset = (uint64_t)BaseOffset + MinOffset;
1664 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1667 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1670 HasBaseReg, Scale) &&
1676 int64_t MinOffset, int64_t MaxOffset,
1677 LSRUse::KindType Kind, MemAccessTy AccessTy,
1678 const Formula &F,
const Loop &L) {
1686 assert((F.isCanonical(L) || F.Scale != 0));
1688 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1693 int64_t MaxOffset, LSRUse::KindType Kind,
1695 int64_t BaseOffset,
bool HasBaseReg, int64_t Scale) {
1698 BaseOffset, HasBaseReg, Scale) ||
1703 BaseGV, BaseOffset,
true, 0));
1707 int64_t MaxOffset, LSRUse::KindType Kind,
1708 MemAccessTy AccessTy,
const Formula &F) {
1709 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1710 F.BaseOffset, F.HasBaseReg, F.Scale);
1714 const LSRUse &LU,
const Formula &F) {
1717 for (
const LSRFixup &
Fixup : LU.Fixups)
1719 (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
1720 F.Scale, Fixup.UserInst))
1726 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1731 const LSRUse &LU,
const Formula &F,
1740 return F.Scale != 1;
1746 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1747 F.Scale, LU.AccessTy.AddrSpace);
1749 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1750 F.Scale, LU.AccessTy.AddrSpace);
1752 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1753 "Legal addressing mode has an illegal cost!");
1754 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1756 case LSRUse::ICmpZero:
1758 case LSRUse::Special:
1768 LSRUse::KindType Kind, MemAccessTy AccessTy,
1772 if (BaseOffset == 0 && !BaseGV)
return true;
1776 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1780 if (!HasBaseReg && Scale == 1) {
1791 int64_t MaxOffset, LSRUse::KindType Kind,
1792 MemAccessTy AccessTy,
const SCEV *S,
1795 if (S->
isZero())
return true;
1803 if (!S->
isZero())
return false;
1806 if (BaseOffset == 0 && !BaseGV)
return true;
1810 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1813 BaseOffset, HasBaseReg, Scale);
1830 const SCEV *IncExpr;
1833 : UserInst(U), IVOperand(O), IncExpr(E) {}
1840 const SCEV *ExprBase =
nullptr;
1842 IVChain() =
default;
1843 IVChain(
const IVInc &Head,
const SCEV *
Base)
1844 : Incs(1, Head), ExprBase(Base) {}
1849 const_iterator
begin()
const {
1851 return std::next(Incs.
begin());
1853 const_iterator
end()
const {
1858 bool hasIncs()
const {
return Incs.
size() >= 2; }
1867 bool isProfitableIncrement(
const SCEV *OperExpr,
1868 const SCEV *IncExpr,
1888 bool Changed =
false;
1911 RegUseTracker RegUses;
1916 static const unsigned MaxChains = 8;
1924 void OptimizeShadowIV();
1927 void OptimizeLoopTermCond();
1931 void FinalizeChain(IVChain &Chain);
1932 void CollectChains();
1936 void CollectInterestingTypesAndFactors();
1937 void CollectFixupsAndInitialFormulae();
1943 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
bool HasBaseReg,
1944 LSRUse::KindType Kind, MemAccessTy AccessTy);
1946 std::pair<size_t, int64_t> getUse(
const SCEV *&Expr, LSRUse::KindType Kind,
1947 MemAccessTy AccessTy);
1949 void DeleteUse(LSRUse &LU,
size_t LUIdx);
1951 LSRUse *FindUseWithSimilarFormula(
const Formula &F,
const LSRUse &OrigLU);
1953 void InsertInitialFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx);
1954 void InsertSupplementalFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx);
1955 void CountRegisters(
const Formula &F,
size_t LUIdx);
1956 bool InsertFormula(LSRUse &LU,
unsigned LUIdx,
const Formula &F);
1958 void CollectLoopInvariantFixupsAndFormulae();
1960 void GenerateReassociations(LSRUse &LU,
unsigned LUIdx, Formula
Base,
1961 unsigned Depth = 0);
1963 void GenerateReassociationsImpl(LSRUse &LU,
unsigned LUIdx,
1964 const Formula &Base,
unsigned Depth,
1965 size_t Idx,
bool IsScaledReg =
false);
1966 void GenerateCombinations(LSRUse &LU,
unsigned LUIdx, Formula Base);
1967 void GenerateSymbolicOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
1968 const Formula &Base,
size_t Idx,
1969 bool IsScaledReg =
false);
1970 void GenerateSymbolicOffsets(LSRUse &LU,
unsigned LUIdx, Formula Base);
1971 void GenerateConstantOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
1972 const Formula &Base,
1974 size_t Idx,
bool IsScaledReg =
false);
1975 void GenerateConstantOffsets(LSRUse &LU,
unsigned LUIdx, Formula Base);
1976 void GenerateICmpZeroScales(LSRUse &LU,
unsigned LUIdx, Formula Base);
1977 void GenerateScales(LSRUse &LU,
unsigned LUIdx, Formula Base);
1978 void GenerateTruncates(LSRUse &LU,
unsigned LUIdx, Formula Base);
1979 void GenerateCrossUseConstantOffsets();
1980 void GenerateAllReuseFormulae();
1982 void FilterOutUndesirableDedicatedRegisters();
1984 size_t EstimateSearchSpaceComplexity()
const;
1985 void NarrowSearchSpaceByDetectingSupersets();
1986 void NarrowSearchSpaceByCollapsingUnrolledCode();
1987 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1988 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
1989 void NarrowSearchSpaceByDeletingCostlyFormulas();
1990 void NarrowSearchSpaceByPickingWinnerRegs();
1991 void NarrowSearchSpaceUsingHeuristics();
1996 const Cost &CurCost,
2010 Value *Expand(
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
2013 void RewriteForPHI(
PHINode *PN,
const LSRUse &LU,
const LSRFixup &LF,
2016 void Rewrite(
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
2025 bool getChanged()
const {
return Changed; }
2027 void print_factors_and_types(
raw_ostream &OS)
const;
2038 void LSRInstance::OptimizeShadowIV() {
2040 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2048 Type *DestTy =
nullptr;
2049 bool IsSigned =
false;
2063 if (
UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
2065 DestTy = UCast->getDestTy();
2067 else if (
SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
2069 DestTy = SCast->getDestTy();
2071 if (!DestTy)
continue;
2091 if (Mantissa == -1)
continue;
2095 unsigned Entry, Latch;
2105 if (!Init)
continue;
2112 if (!Incr)
continue;
2114 && Incr->getOpcode() != Instruction::Sub)
2119 if (Incr->getOperand(0) == PH)
2120 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2121 else if (Incr->getOperand(1) == PH)
2122 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2139 Instruction::FAdd : Instruction::FSub,
2140 NewPH, CFP,
"IV.S.next.", Incr);
2157 if (U.getUser() == Cond) {
2222 if (!Sel || !Sel->
hasOneUse())
return Cond;
2225 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2230 const SCEV *IterationCount = SE.
getAddExpr(One, BackedgeTakenCount);
2231 if (IterationCount != SE.
getSCEV(Sel))
return Cond;
2238 if (
const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2241 }
else if (
const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2244 }
else if (
const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2276 "Loop condition operand is an addrec in a different loop!");
2280 Value *NewRHS =
nullptr;
2284 if (
ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2285 if (BO1->isOne() && SE.
getSCEV(BO->getOperand(0)) == MaxRHS)
2286 NewRHS = BO->getOperand(0);
2288 if (
ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2289 if (BO1->isOne() && SE.
getSCEV(BO->getOperand(0)) == MaxRHS)
2290 NewRHS = BO->getOperand(0);
2297 else if (
const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2298 NewRHS = SU->getValue();
2326 LSRInstance::OptimizeLoopTermCond() {
2345 return LatchBlock != BB;
2353 for (
BasicBlock *ExitingBlock : ExitingBlocks) {
2369 if (!FindIVUserForCond(Cond, CondUse))
2378 Cond = OptimizeMax(Cond, CondUse);
2383 if (!DT.
dominates(ExitingBlock, LatchBlock))
2388 if (LatchBlock != ExitingBlock)
2392 if (&*UI != CondUse &&
2396 const SCEV *A = IU.getStride(*CondUse, L);
2397 const SCEV *
B = IU.getStride(*UI, L);
2398 if (!A || !B)
continue;
2408 dyn_cast_or_null<SCEVConstant>(
getExactSDiv(B, A, SE))) {
2412 goto decline_post_inc;
2416 goto decline_post_inc;
2418 if (
isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) {
2420 TTI, UI->getUser(), UI->getOperandValToReplace());
2425 AccessTy.AddrSpace))
2426 goto decline_post_inc;
2431 AccessTy.AddrSpace))
2432 goto decline_post_inc;
2437 LLVM_DEBUG(
dbgs() <<
" Change loop exiting icmp to use postinc iv: " 2449 Cond = cast<ICmpInst>(Cond->
clone());
2451 ExitingBlock->getInstList().insert(TermBr->
getIterator(), Cond);
2478 IVIncInsertPos = Inst;
2479 else if (BB != IVIncInsertPos->
getParent())
2486 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2487 bool HasBaseReg, LSRUse::KindType Kind,
2488 MemAccessTy AccessTy) {
2489 int64_t NewMinOffset = LU.MinOffset;
2490 int64_t NewMaxOffset = LU.MaxOffset;
2491 MemAccessTy NewAccessTy = AccessTy;
2496 if (LU.Kind != Kind)
2503 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2504 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2505 AccessTy.AddrSpace);
2510 if (NewOffset < LU.MinOffset) {
2512 LU.MaxOffset - NewOffset, HasBaseReg))
2514 NewMinOffset = NewOffset;
2515 }
else if (NewOffset > LU.MaxOffset) {
2517 NewOffset - LU.MinOffset, HasBaseReg))
2519 NewMaxOffset = NewOffset;
2523 LU.MinOffset = NewMinOffset;
2524 LU.MaxOffset = NewMaxOffset;
2525 LU.AccessTy = NewAccessTy;
2532 std::pair<size_t, int64_t> LSRInstance::getUse(
const SCEV *&Expr,
2533 LSRUse::KindType Kind,
2534 MemAccessTy AccessTy) {
2535 const SCEV *Copy = Expr;
2545 std::pair<UseMapTy::iterator, bool>
P =
2549 size_t LUIdx = P.first->second;
2550 LSRUse &LU = Uses[LUIdx];
2551 if (reconcileNewOffset(LU, Offset,
true, Kind, AccessTy))
2553 return std::make_pair(LUIdx, Offset);
2557 size_t LUIdx = Uses.size();
2558 P.first->second = LUIdx;
2559 Uses.push_back(LSRUse(Kind, AccessTy));
2560 LSRUse &LU = Uses[LUIdx];
2564 return std::make_pair(LUIdx, Offset);
2568 void LSRInstance::DeleteUse(LSRUse &LU,
size_t LUIdx) {
2569 if (&LU != &Uses.back())
2574 RegUses.swapAndDropUse(LUIdx, Uses.size());
2580 LSRInstance::FindUseWithSimilarFormula(
const Formula &OrigF,
2581 const LSRUse &OrigLU) {
2583 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2584 LSRUse &LU = Uses[LUIdx];
2590 if (&LU != &OrigLU &&
2591 LU.Kind != LSRUse::ICmpZero &&
2592 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2593 LU.WidestFixupType == OrigLU.WidestFixupType &&
2594 LU.HasFormulaWithSameRegs(OrigF)) {
2596 for (
const Formula &F : LU.Formulae) {
2599 if (F.BaseRegs == OrigF.BaseRegs &&
2600 F.ScaledReg == OrigF.ScaledReg &&
2601 F.BaseGV == OrigF.BaseGV &&
2602 F.Scale == OrigF.Scale &&
2603 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2604 if (F.BaseOffset == 0)
2619 void LSRInstance::CollectInterestingTypesAndFactors() {
2625 const SCEV *Expr = IU.getExpr(U);
2635 if (AR->getLoop() == L)
2636 Strides.
insert(AR->getStepRecurrence(SE));
2641 }
while (!Worklist.
empty());
2646 I = Strides.
begin(),
E = Strides.
end(); I !=
E; ++
I)
2648 std::next(I); NewStrideIter !=
E; ++NewStrideIter) {
2649 const SCEV *OldStride = *
I;
2650 const SCEV *NewStride = *NewStrideIter;
2661 dyn_cast_or_null<SCEVConstant>(
getExactSDiv(NewStride, OldStride,
2663 if (Factor->getAPInt().getMinSignedBits() <= 64)
2664 Factors.insert(Factor->getAPInt().getSExtValue());
2669 if (Factor->getAPInt().getMinSignedBits() <= 64)
2670 Factors.insert(Factor->getAPInt().getSExtValue());
2676 if (Types.size() == 1)
2688 for(; OI != OE; ++OI) {
2689 if (
Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2694 dyn_cast<SCEVAddRecExpr>(SE.
getSCEV(Oper))) {
2695 if (AR->getLoop() == L)
2706 if (
TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2707 return Trunc->getOperand(0);
2740 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2742 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2744 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2750 for (std::reverse_iterator<SCEVAddExpr::op_iterator>
I(Add->
op_end()),
2752 const SCEV *SubExpr = *
I;
2762 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2771 bool IVChain::isProfitableIncrement(
const SCEV *OperExpr,
2772 const SCEV *IncExpr,
2780 if (!isa<SCEVConstant>(IncExpr)) {
2782 if (isa<SCEVConstant>(SE.
getMinusSCEV(OperExpr, HeadExpr)))
2806 if (!Chain.hasIncs())
2809 if (!Users.
empty()) {
2810 LLVM_DEBUG(
dbgs() <<
"Chain: " << *Chain.Incs[0].UserInst <<
" users:\n";
2812 : Users) {
dbgs() <<
" " << *Inst <<
"\n"; });
2815 assert(!Chain.Incs.empty() &&
"empty IV chains are not allowed");
2823 if (isa<PHINode>(Chain.tailUserInst())
2824 && SE.
getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2827 const SCEV *LastIncExpr =
nullptr;
2828 unsigned NumConstIncrements = 0;
2829 unsigned NumVarIncrements = 0;
2830 unsigned NumReusedIncrements = 0;
2831 for (
const IVInc &Inc : Chain) {
2832 if (Inc.IncExpr->isZero())
2837 if (isa<SCEVConstant>(Inc.IncExpr)) {
2838 ++NumConstIncrements;
2842 if (Inc.IncExpr == LastIncExpr)
2843 ++NumReusedIncrements;
2847 LastIncExpr = Inc.IncExpr;
2852 if (NumConstIncrements > 1)
2859 cost += NumVarIncrements;
2863 cost -= NumReusedIncrements;
2865 LLVM_DEBUG(
dbgs() <<
"Chain: " << *Chain.Incs[0].UserInst <<
" Cost: " << cost
2882 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2883 const SCEV *LastIncExpr =
nullptr;
2884 for (; ChainIdx < NChains; ++ChainIdx) {
2885 IVChain &Chain = IVChainVec[ChainIdx];
2891 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2899 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2908 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2909 LastIncExpr = IncExpr;
2915 if (ChainIdx == NChains) {
2916 if (isa<PHINode>(UserInst))
2918 if (NChains >= MaxChains && !StressIVChain) {
2922 LastIncExpr = OperExpr;
2926 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2929 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2931 ChainUsersVec.
resize(NChains);
2932 LLVM_DEBUG(
dbgs() <<
"IV Chain#" << ChainIdx <<
" Head: (" << *UserInst
2933 <<
") IV=" << *LastIncExpr <<
"\n");
2935 LLVM_DEBUG(
dbgs() <<
"IV Chain#" << ChainIdx <<
" Inc: (" << *UserInst
2936 <<
") IV+" << *LastIncExpr <<
"\n");
2938 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2940 IVChain &Chain = IVChainVec[ChainIdx];
2944 if (!LastIncExpr->
isZero()) {
2945 ChainUsersVec[ChainIdx].FarUsers.
insert(NearUsers.
begin(),
2961 IVChain::const_iterator IncIter = Chain.Incs.begin();
2962 IVChain::const_iterator IncEnd = Chain.Incs.end();
2963 for( ; IncIter != IncEnd; ++IncIter) {
2964 if (IncIter->UserInst == OtherUse)
2967 if (IncIter != IncEnd)
2971 && !isa<SCEVUnknown>(SE.
getSCEV(OtherUse))
2972 && IU.isIVUserOrOperand(OtherUse)) {
2975 NearUsers.
insert(OtherUse);
2980 ChainUsersVec[ChainIdx].FarUsers.
erase(UserInst);
3005 void LSRInstance::CollectChains() {
3012 Rung->
getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3021 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
3031 for (
unsigned ChainIdx = 0, NChains = IVChainVec.size();
3032 ChainIdx < NChains; ++ChainIdx) {
3033 ChainUsersVec[ChainIdx].NearUsers.
erase(&I);
3039 while (IVOpIter != IVOpEnd) {
3040 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
3041 if (UniqueOperands.
insert(IVOpInst).second)
3042 ChainInstruction(&I, IVOpInst, ChainUsersVec);
3043 IVOpIter =
findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3055 ChainInstruction(&PN, IncV, ChainUsersVec);
3058 unsigned ChainIdx = 0;
3059 for (
unsigned UsersIdx = 0, NChains = IVChainVec.size();
3060 UsersIdx < NChains; ++UsersIdx) {
3062 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
3065 if (ChainIdx != UsersIdx)
3066 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3067 FinalizeChain(IVChainVec[ChainIdx]);
3070 IVChainVec.resize(ChainIdx);
3073 void LSRInstance::FinalizeChain(IVChain &Chain) {
3074 assert(!Chain.Incs.empty() &&
"empty IV chains are not allowed");
3075 LLVM_DEBUG(
dbgs() <<
"Final Chain: " << *Chain.Incs[0].UserInst <<
"\n");
3077 for (
const IVInc &Inc : Chain) {
3079 auto UseI =
find(Inc.UserInst->operands(), Inc.IVOperand);
3080 assert(UseI != Inc.UserInst->op_end() &&
"cannot find IV operand");
3081 IVIncSet.insert(UseI);
3089 if (!IncConst || !
isAddressUse(TTI, UserInst, Operand))
3095 MemAccessTy AccessTy =
getAccessType(TTI, UserInst, Operand);
3110 const IVInc &Head = Chain.Incs[0];
3115 Value *IVSrc =
nullptr;
3116 while (IVOpIter != IVOpEnd) {
3127 if (SE.
getSCEV(*IVOpIter) == Head.IncExpr
3128 || SE.
getSCEV(IVSrc) == Head.IncExpr) {
3131 IVOpIter =
findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3133 if (IVOpIter == IVOpEnd) {
3135 LLVM_DEBUG(
dbgs() <<
"Concealed chain head: " << *Head.UserInst <<
"\n");
3140 Type *IVTy = IVSrc->getType();
3142 const SCEV *LeftOverExpr =
nullptr;
3143 for (
const IVInc &Inc : Chain) {
3145 if (isa<PHINode>(InsertPt))
3146 InsertPt = L->getLoopLatch()->getTerminator();
3150 Value *IVOper = IVSrc;
3151 if (!Inc.IncExpr->isZero()) {
3155 LeftOverExpr = LeftOverExpr ?
3156 SE.
getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3158 if (LeftOverExpr && !LeftOverExpr->
isZero()) {
3164 IVOper = Rewriter.
expandCodeFor(IVOperExpr, IVTy, InsertPt);
3168 assert(IVTy == IVOper->
getType() &&
"inconsistent IV increment type");
3170 LeftOverExpr =
nullptr;
3173 Type *OperTy = Inc.IVOperand->getType();
3174 if (IVTy != OperTy) {
3176 "cannot extend a chained IV");
3178 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy,
"lsr.chain");
3180 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3185 if (isa<PHINode>(Chain.tailUserInst())) {
3186 for (
PHINode &Phi : L->getHeader()->phis()) {
3190 Phi.getIncomingValueForBlock(L->getLoopLatch()));
3193 Value *IVOper = IVSrc;
3195 if (IVTy != PostIncTy) {
3197 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3199 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy,
"lsr.chain");
3201 Phi.replaceUsesOfWith(PostIncV, IVOper);
3207 void LSRInstance::CollectFixupsAndInitialFormulae() {
3212 find(UserInst->
operands(), U.getOperandValToReplace());
3213 assert(UseI != UserInst->
op_end() &&
"cannot find IV operand");
3214 if (IVIncSet.count(UseI)) {
3215 LLVM_DEBUG(
dbgs() <<
"Use is in profitable chain: " << **UseI <<
'\n');
3220 MemAccessTy AccessTy;
3221 if (
isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
3223 AccessTy =
getAccessType(TTI, UserInst, U.getOperandValToReplace());
3226 const SCEV *S = IU.getExpr(U);
3235 if (
ICmpInst *CI = dyn_cast<ICmpInst>(UserInst))
3236 if (CI->isEquality()) {
3239 Value *
NV = CI->getOperand(1);
3240 if (NV == U.getOperandValToReplace()) {
3241 CI->setOperand(1, CI->getOperand(0));
3242 CI->setOperand(0, NV);
3243 NV = CI->getOperand(1);
3253 Kind = LSRUse::ICmpZero;
3259 for (
size_t i = 0, e = Factors.size(); i != e; ++i)
3260 if (Factors[i] != -1)
3261 Factors.insert(-(uint64_t)Factors[i]);
3266 std::pair<size_t, int64_t>
P = getUse(S, Kind, AccessTy);
3267 size_t LUIdx = P.first;
3268 int64_t
Offset = P.second;
3269 LSRUse &LU = Uses[LUIdx];
3272 LSRFixup &LF = LU.getNewFixup();
3273 LF.UserInst = UserInst;
3274 LF.OperandValToReplace = U.getOperandValToReplace();
3275 LF.PostIncLoops = TmpPostIncLoops;
3277 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3279 if (!LU.WidestFixupType ||
3282 LU.WidestFixupType = LF.OperandValToReplace->getType();
3285 if (LU.Formulae.empty()) {
3286 InsertInitialFormula(S, LU, LUIdx);
3287 CountRegisters(LU.Formulae.back(), LUIdx);
3297 LSRInstance::InsertInitialFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx) {
3300 LU.RigidFormula =
true;
3303 F.initialMatch(S, L, SE);
3304 bool Inserted = InsertFormula(LU, LUIdx, F);
3305 assert(Inserted &&
"Initial formula already exists!"); (void)Inserted;
3311 LSRInstance::InsertSupplementalFormula(
const SCEV *S,
3312 LSRUse &LU,
size_t LUIdx) {
3314 F.BaseRegs.push_back(S);
3315 F.HasBaseReg =
true;
3316 bool Inserted = InsertFormula(LU, LUIdx, F);
3317 assert(Inserted &&
"Supplemental formula already exists!"); (void)Inserted;
3321 void LSRInstance::CountRegisters(
const Formula &F,
size_t LUIdx) {
3323 RegUses.countRegister(F.ScaledReg, LUIdx);
3324 for (
const SCEV *BaseReg : F.BaseRegs)
3325 RegUses.countRegister(BaseReg, LUIdx);
3330 bool LSRInstance::InsertFormula(LSRUse &LU,
unsigned LUIdx,
const Formula &F) {
3332 assert(
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3333 "Formula is illegal");
3335 if (!LU.InsertFormula(F, *L))
3338 CountRegisters(F, LUIdx);
3348 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3352 while (!Worklist.empty()) {
3353 const SCEV *S = Worklist.pop_back_val();
3356 if (!Visited.
insert(S).second)
3360 Worklist.append(
N->op_begin(),
N->op_end());
3363 else if (
const SCEVUDivExpr *
D = dyn_cast<SCEVUDivExpr>(S)) {
3364 Worklist.push_back(
D->getLHS());
3365 Worklist.push_back(
D->getRHS());
3366 }
else if (
const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3367 const Value *V = US->getValue();
3368 if (
const Instruction *Inst = dyn_cast<Instruction>(V)) {
3371 }
else if (isa<UndefValue>(V))
3374 for (
const Use &U : V->
uses()) {
3384 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3386 cast<PHINode>(UserInst)->getIncomingBlock(
3399 const SCEV *UserS = SE.
getSCEV(const_cast<Instruction *>(UserInst));
3401 if (!isa<SCEVUnknown>(UserS))
3405 SE.
getUnknown(const_cast<Instruction *>(UserInst)));
3410 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3411 unsigned OtherIdx = !U.getOperandNo();
3412 Value *OtherOp =
const_cast<Value *
>(ICI->getOperand(OtherIdx));
3417 std::pair<size_t, int64_t>
P = getUse(
3419 size_t LUIdx = P.first;
3420 int64_t
Offset = P.second;
3421 LSRUse &LU = Uses[LUIdx];
3422 LSRFixup &LF = LU.getNewFixup();
3423 LF.UserInst =
const_cast<Instruction *
>(UserInst);
3424 LF.OperandValToReplace = U;
3426 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3427 if (!LU.WidestFixupType ||
3430 LU.WidestFixupType = LF.OperandValToReplace->getType();
3431 InsertSupplementalFormula(US, LU, LUIdx);
3432 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3448 unsigned Depth = 0) {
3455 for (
const SCEV *S :
Add->operands()) {
3461 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3463 if (AR->getStart()->isZero() || !AR->isAffine())
3470 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3471 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3472 Remainder =
nullptr;
3474 if (Remainder != AR->getStart()) {
3476 Remainder = SE.getConstant(AR->getType(), 0);
3477 return SE.getAddRecExpr(Remainder,
3478 AR->getStepRecurrence(SE),
3483 }
else if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3485 if (Mul->getNumOperands() != 2)
3488 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3489 C = C ? cast<SCEVConstant>(SE.
getMulExpr(C, Op0)) : Op0;
3490 const SCEV *Remainder =
3493 Ops.push_back(SE.getMulExpr(C, Remainder));
3503 LSRUse &LU,
const SCEV *S,
const Loop *L,
3506 !LU.AccessTy.getType()->isIntOrIntVectorTy())
3512 if (!isa<SCEVConstant>(LoopStep))
3514 if (LU.AccessTy.getType()->getScalarSizeInBits() !=
3521 if (!isa<SCEVConstant>(LoopStart) && SE.
isLoopInvariant(LoopStart, L))
3528 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU,
unsigned LUIdx,
3529 const Formula &
Base,
3530 unsigned Depth,
size_t Idx,
3532 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3544 if (AddOps.
size() == 1)
3558 LU.AccessTy, *J, Base.getNumRegs() > 1))
3564 InnerAddOps.
append(std::next(J),
3569 if (InnerAddOps.
size() == 1 &&
3571 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3587 F.ScaledReg =
nullptr;
3589 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3590 }
else if (IsScaledReg)
3591 F.ScaledReg = InnerSum;
3593 F.BaseRegs[Idx] = InnerSum;
3603 F.BaseRegs.push_back(*J);
3608 if (InsertFormula(LU, LUIdx, F))
3615 GenerateReassociations(LU, LUIdx, LU.Formulae.back(),
3621 void LSRInstance::GenerateReassociations(LSRUse &LU,
unsigned LUIdx,
3622 Formula Base,
unsigned Depth) {
3623 assert(Base.isCanonical(*L) &&
"Input must be in the canonical form");
3628 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3629 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3631 if (Base.Scale == 1)
3632 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3638 void LSRInstance::GenerateCombinations(LSRUse &LU,
unsigned LUIdx,
3641 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3650 for (
const SCEV *BaseReg : Base.BaseRegs) {
3655 F.BaseRegs.push_back(BaseReg);
3657 if (Ops.
size() > 1) {
3663 F.BaseRegs.push_back(Sum);
3665 (void)InsertFormula(LU, LUIdx, F);
3671 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
3672 const Formula &Base,
size_t Idx,
3674 const SCEV *
G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3680 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3685 F.BaseRegs[Idx] =
G;
3686 (void)InsertFormula(LU, LUIdx, F);
3690 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU,
unsigned LUIdx,
3693 if (Base.BaseGV)
return;
3695 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3696 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3697 if (Base.Scale == 1)
3698 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, -1,
3703 void LSRInstance::GenerateConstantOffsetsImpl(
3704 LSRUse &LU,
unsigned LUIdx,
const Formula &Base,
3706 const SCEV *
G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3707 for (int64_t
Offset : Worklist) {
3709 F.BaseOffset = (uint64_t)Base.BaseOffset -
Offset;
3718 F.ScaledReg =
nullptr;
3720 F.deleteBaseReg(F.BaseRegs[Idx]);
3722 }
else if (IsScaledReg)
3725 F.BaseRegs[Idx] = NewG;
3727 (void)InsertFormula(LU, LUIdx, F);
3732 if (G->
isZero() || Imm == 0)
3735 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3736 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3741 F.BaseRegs[Idx] =
G;
3742 (void)InsertFormula(LU, LUIdx, F);
3746 void LSRInstance::GenerateConstantOffsets(LSRUse &LU,
unsigned LUIdx,
3752 if (LU.MaxOffset != LU.MinOffset)
3755 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3756 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3757 if (Base.Scale == 1)
3758 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, -1,
3764 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU,
unsigned LUIdx,
3766 if (LU.Kind != LSRUse::ICmpZero)
return;
3769 Type *IntTy = Base.getType();
3774 if (LU.MinOffset != LU.MaxOffset)
return;
3777 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
3779 for (
const SCEV *BaseReg : Base.BaseRegs)
3782 assert(!Base.BaseGV &&
"ICmpZero use is not legal!");
3785 for (int64_t Factor : Factors) {
3787 if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1)
3789 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3790 if (NewBaseOffset / Factor != Base.BaseOffset)
3798 int64_t
Offset = LU.MinOffset;
3799 if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1)
3801 Offset = (uint64_t)Offset * Factor;
3802 if (Offset / Factor != LU.MinOffset)
3810 F.BaseOffset = NewBaseOffset;
3813 if (!
isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3817 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3822 for (
size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3823 F.BaseRegs[i] = SE.
getMulExpr(F.BaseRegs[i], FactorS);
3824 if (
getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3830 F.ScaledReg = SE.
getMulExpr(F.ScaledReg, FactorS);
3831 if (
getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3836 if (F.UnfoldedOffset != 0) {
3837 if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() &&
3840 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3841 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3850 (void)InsertFormula(LU, LUIdx, F);
3857 void LSRInstance::GenerateScales(LSRUse &LU,
unsigned LUIdx, Formula Base) {
3859 Type *IntTy = Base.getType();
3864 if (Base.Scale != 0 && !Base.unscale())
3867 assert(Base.Scale == 0 &&
"unscale did not did its job!");
3870 for (int64_t Factor : Factors) {
3871 Base.Scale = Factor;
3872 Base.HasBaseReg = Base.BaseRegs.size() > 1;
3874 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3879 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3880 LU.AccessTy, Base) &&
3881 LU.AllFixupsOutsideLoop)
3882 LU.Kind = LSRUse::Special;
3888 if (LU.Kind == LSRUse::ICmpZero &&
3889 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3892 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
3894 if (AR && (AR->
getLoop() == L || LU.AllFixupsOutsideLoop)) {
3903 F.ScaledReg = Quotient;
3904 F.deleteBaseReg(F.BaseRegs[i]);
3908 if (F.Scale == 1 && (F.BaseRegs.empty() ||
3909 (AR->
getLoop() != L && LU.AllFixupsOutsideLoop)))
3913 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
3915 (void)InsertFormula(LU, LUIdx, F);
3923 void LSRInstance::GenerateTruncates(LSRUse &LU,
unsigned LUIdx, Formula Base) {
3925 if (Base.BaseGV)
return;
3928 Type *DstTy = Base.getType();
3932 for (
Type *SrcTy : Types) {
3937 for (
const SCEV *&BaseReg : F.BaseRegs)
3942 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3946 (void)InsertFormula(LU, LUIdx, F);
3959 const SCEV *OrigReg;
3961 WorkItem(
size_t LI, int64_t I,
const SCEV *R)
3962 : LUIdx(LI), Imm(I), OrigReg(R) {}
3970 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 3972 OS <<
"in formulae referencing " << *OrigReg <<
" in use " << LUIdx
3973 <<
" , add offset " << Imm;
3983 void LSRInstance::GenerateCrossUseConstantOffsets() {
3985 using ImmMapTy = std::map<int64_t, const SCEV *>;
3990 for (
const SCEV *
Use : RegUses) {
3993 auto Pair = Map.
insert(std::make_pair(Reg, ImmMapTy()));
3996 Pair.first->second.insert(std::make_pair(Imm,
Use));
3997 UsedByIndicesMap[
Reg] |= RegUses.getUsedByIndices(
Use);
4005 for (
const SCEV *Reg : Sequence) {
4006 const ImmMapTy &Imms = Map.
find(Reg)->second;
4009 if (Imms.size() == 1)
4012 LLVM_DEBUG(
dbgs() <<
"Generating cross-use offsets for " << *Reg <<
':';
4013 for (
const auto &Entry
4015 <<
' ' << Entry.first;
4019 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4021 const SCEV *OrigReg = J->second;
4023 int64_t JImm = J->first;
4024 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
4026 if (!isa<SCEVConstant>(OrigReg) &&
4027 UsedByIndicesMap[Reg].
count() == 1) {
4035 ImmMapTy::const_iterator OtherImms[] = {
4036 Imms.begin(), std::prev(Imms.end()),
4037 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->
first) /
4041 ImmMapTy::const_iterator M = OtherImms[i];
4042 if (M == J || M == JE)
continue;
4045 int64_t Imm = (uint64_t)JImm - M->first;
4048 if (UniqueItems.
insert(std::make_pair(LUIdx, Imm)).second)
4049 WorkItems.
push_back(WorkItem(LUIdx, Imm, OrigReg));
4056 UsedByIndicesMap.
clear();
4057 UniqueItems.
clear();
4060 for (
const WorkItem &WI : WorkItems) {
4061 size_t LUIdx = WI.LUIdx;
4062 LSRUse &LU = Uses[LUIdx];
4063 int64_t Imm = WI.Imm;
4064 const SCEV *OrigReg = WI.OrigReg;
4071 for (
size_t L = 0,
LE = LU.Formulae.size(); L !=
LE; ++L) {
4072 Formula F = LU.Formulae[L];
4079 if (F.ScaledReg == OrigReg) {
4080 int64_t
Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
4082 if (F.referencesReg(SE.
getSCEV(
4086 NewF.BaseOffset =
Offset;
4087 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4090 NewF.ScaledReg = SE.
getAddExpr(NegImmS, NewF.ScaledReg);
4095 if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
4096 if (
C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
4097 (
C->getAPInt().abs() *
APInt(BitWidth, F.Scale))
4102 NewF.canonicalize(*this->L);
4103 (void)InsertFormula(LU, LUIdx, NewF);
4106 for (
size_t N = 0,
NE = F.BaseRegs.size();
N !=
NE; ++
N) {
4107 const SCEV *BaseReg = F.BaseRegs[
N];
4108 if (BaseReg != OrigReg)
4111 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
4113 LU.Kind, LU.AccessTy, NewF)) {
4120 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
4122 NewF.BaseRegs[
N] = SE.
getAddExpr(NegImmS, BaseReg);
4127 for (
const SCEV *NewReg : NewF.BaseRegs)
4129 if ((
C->getAPInt() + NewF.BaseOffset)
4133 countTrailingZeros<uint64_t>(NewF.BaseOffset))
4137 NewF.canonicalize(*this->L);
4138 (void)InsertFormula(LU, LUIdx, NewF);
4149 LSRInstance::GenerateAllReuseFormulae() {
4152 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4153 LSRUse &LU = Uses[LUIdx];
4154 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4155 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4156 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4157 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4159 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4160 LSRUse &LU = Uses[LUIdx];
4161 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4162 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4163 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4164 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4165 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4166 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4167 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4168 GenerateScales(LU, LUIdx, LU.Formulae[i]);
4170 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4171 LSRUse &LU = Uses[LUIdx];
4172 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4173 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4176 GenerateCrossUseConstantOffsets();
4179 "After generating reuse formulae:\n";
4180 print_uses(
dbgs()));
4185 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4190 bool ChangedFormulae =
false;
4195 using BestFormulaeTy =
4198 BestFormulaeTy BestFormulae;
4200 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4201 LSRUse &LU = Uses[LUIdx];
4206 for (
size_t FIdx = 0, NumForms = LU.Formulae.size();
4207 FIdx != NumForms; ++FIdx) {
4208 Formula &F = LU.Formulae[FIdx];
4219 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs);
4220 if (CostF.isLoser()) {
4232 for (
const SCEV *Reg : F.BaseRegs) {
4233 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4237 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4243 std::pair<BestFormulaeTy::const_iterator, bool>
P =
4244 BestFormulae.insert(std::make_pair(Key, FIdx));
4248 Formula &Best = LU.Formulae[P.first->second];
4252 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU);
4253 if (CostF.isLess(CostBest, TTI))
4257 " in favor of formula ";
4258 Best.print(
dbgs());
dbgs() <<
'\n');
4261 ChangedFormulae =
true;
4263 LU.DeleteFormula(F);
4271 LU.RecomputeRegs(LUIdx, RegUses);
4274 BestFormulae.clear();
4279 "After filtering out undesirable candidates:\n";
4290 size_t LSRInstance::EstimateSearchSpaceComplexity()
const {
4292 for (
const LSRUse &LU : Uses) {
4293 size_t FSize = LU.Formulae.size();
4294 if (FSize >= ComplexityLimit) {
4299 if (Power >= ComplexityLimit)
4308 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4309 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4312 LLVM_DEBUG(
dbgs() <<
"Narrowing the search space by eliminating formulae " 4313 "which use a superset of registers used by other " 4316 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4317 LSRUse &LU = Uses[LUIdx];
4319 for (
size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4320 Formula &F = LU.Formulae[i];
4325 I = F.BaseRegs.begin(),
E = F.BaseRegs.end(); I !=
E; ++
I) {
4328 NewF.BaseOffset +=
C->getValue()->getSExtValue();
4329 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4330 (I - F.BaseRegs.begin()));
4331 if (LU.HasFormulaWithSameRegs(NewF)) {
4334 LU.DeleteFormula(F);
4340 }
else if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4341 if (
GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4345 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4346 (I - F.BaseRegs.begin()));
4347 if (LU.HasFormulaWithSameRegs(NewF)) {
4350 LU.DeleteFormula(F);
4361 LU.RecomputeRegs(LUIdx, RegUses);
4370 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4371 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4375 dbgs() <<
"The search space is too complex.\n" 4376 "Narrowing the search space by assuming that uses separated " 4377 "by a constant offset will use the same registers.\n");
4381 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4382 LSRUse &LU = Uses[LUIdx];
4383 for (
const Formula &F : LU.Formulae) {
4384 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4387 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4391 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset,
false,
4392 LU.Kind, LU.AccessTy))
4397 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4400 for (LSRFixup &Fixup : LU.Fixups) {
4401 Fixup.Offset += F.BaseOffset;
4402 LUThatHas->pushFixup(Fixup);
4403 LLVM_DEBUG(
dbgs() <<
"New fixup has offset " << Fixup.Offset <<
'\n');
4408 for (
size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4409 Formula &F = LUThatHas->Formulae[i];
4410 if (!
isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4411 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4413 LUThatHas->DeleteFormula(F);
4421 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4424 DeleteUse(LU, LUIdx);
4437 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4438 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4441 LLVM_DEBUG(
dbgs() <<
"Narrowing the search space by re-filtering out " 4442 "undesirable dedicated registers.\n");
4444 FilterOutUndesirableDedicatedRegisters();
4459 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4460 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4464 dbgs() <<
"The search space is too complex.\n" 4465 "Narrowing the search space by choosing the best Formula " 4466 "from the Formulae with the same Scale and ScaledReg.\n");
4471 BestFormulaeTy BestFormulae;
4473 bool ChangedFormulae =
false;
4478 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4479 LSRUse &LU = Uses[LUIdx];
4484 auto IsBetterThan = [&](Formula &FA, Formula &FB) {
4489 size_t FARegNum = 0;
4490 for (
const SCEV *Reg : FA.BaseRegs) {
4491 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4492 FARegNum += (NumUses - UsedByIndices.
count() + 1);
4494 size_t FBRegNum = 0;
4495 for (
const SCEV *Reg : FB.BaseRegs) {
4496 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4497 FBRegNum += (NumUses - UsedByIndices.
count() + 1);
4499 if (FARegNum != FBRegNum)
4500 return FARegNum < FBRegNum;
4504 Cost CostFA, CostFB;
4506 CostFA.RateFormula(TTI, FA, Regs, VisitedRegs, L, SE, DT, LU);
4508 CostFB.RateFormula(TTI, FB, Regs, VisitedRegs, L, SE, DT, LU);
4509 return CostFA.isLess(CostFB, TTI);
4513 for (
size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4515 Formula &F = LU.Formulae[FIdx];
4518 auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
4522 Formula &Best = LU.Formulae[
P.first->second];
4523 if (IsBetterThan(F, Best))
4527 " in favor of formula ";
4528 Best.print(
dbgs());
dbgs() <<
'\n');
4530 ChangedFormulae =
true;
4532 LU.DeleteFormula(F);
4538 LU.RecomputeRegs(LUIdx, RegUses);
4541 BestFormulae.clear();
4546 "After filtering out undesirable candidates:\n";
4593 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4594 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4607 for (
const SCEV *Reg : RegUses) {
4608 if (UniqRegs.
count(Reg))
4611 for (
const LSRUse &LU : Uses) {
4612 if (!LU.Regs.count(Reg))
4614 float P = LU.getNotSelectedProbability(Reg);
4620 RegNumMap.
insert(std::make_pair(Reg, PNotSel));
4624 dbgs() <<
"Narrowing the search space by deleting costly formulas\n");
4627 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4628 LSRUse &LU = Uses[LUIdx];
4630 if (LU.Formulae.size() < 2)
4635 float FMinRegNum = LU.Formulae[0].getNumRegs();
4636 float FMinARegNum = LU.Formulae[0].getNumRegs();
4638 for (
size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4639 Formula &F = LU.Formulae[i];
4642 for (
const SCEV *BaseReg : F.BaseRegs) {
4643 if (UniqRegs.
count(BaseReg))
4645 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4646 if (isa<SCEVAddRecExpr>(BaseReg))
4648 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4650 if (
const SCEV *ScaledReg = F.ScaledReg) {
4651 if (!UniqRegs.
count(ScaledReg)) {
4653 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4654 if (isa<SCEVAddRecExpr>(ScaledReg))
4656 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4659 if (FMinRegNum > FRegNum ||
4660 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4661 FMinRegNum = FRegNum;
4662 FMinARegNum = FARegNum;
4667 dbgs() <<
" with min reg num " << FMinRegNum <<
'\n');
4669 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4670 while (LU.Formulae.size() != 1) {
4673 LU.Formulae.pop_back();
4675 LU.RecomputeRegs(LUIdx, RegUses);
4676 assert(LU.Formulae.size() == 1 &&
"Should be exactly 1 min regs formula");
4677 Formula &F = LU.Formulae[0];
4680 UniqRegs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
4682 UniqRegs.
insert(F.ScaledReg);
4690 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4694 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4701 const SCEV *Best =
nullptr;
4702 unsigned BestNum = 0;
4703 for (
const SCEV *Reg : RegUses) {
4704 if (Taken.
count(Reg))
4708 BestNum = RegUses.getUsedByIndices(Reg).count();
4710 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4711 if (Count > BestNum) {
4718 LLVM_DEBUG(
dbgs() <<
"Narrowing the search space by assuming " << *Best
4719 <<
" will yield profitable reuse.\n");
4724 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4725 LSRUse &LU = Uses[LUIdx];
4726 if (!LU.Regs.count(Best))
continue;
4729 for (
size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4730 Formula &F = LU.Formulae[i];
4731 if (!F.referencesReg(Best)) {
4733 LU.DeleteFormula(F);
4737 assert(e != 0 &&
"Use has no formulae left! Is Regs inconsistent?");
4743 LU.RecomputeRegs(LUIdx, RegUses);
4754 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4755 NarrowSearchSpaceByDetectingSupersets();
4756 NarrowSearchSpaceByCollapsingUnrolledCode();
4757 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4759 NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4761 NarrowSearchSpaceByDeletingCostlyFormulas();
4763 NarrowSearchSpaceByPickingWinnerRegs();
4770 const Cost &CurCost,
4783 const LSRUse &LU = Uses[Workspace.
size()];
4790 for (
const SCEV *S : CurRegs)
4791 if (LU.Regs.count(S))
4796 for (
const Formula &F : LU.Formulae) {
4800 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.
size());
4801 for (
const SCEV *Reg : ReqRegs) {
4802 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4805 if (NumReqRegsToFind == 0)
4809 if (NumReqRegsToFind != 0) {
4819 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU);
4820 if (NewCost.isLess(SolutionCost, TTI)) {
4822 if (Workspace.
size() != Uses.size()) {
4823 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4824 NewRegs, VisitedRegs);
4825 if (F.getNumRegs() == 1 && Workspace.
size() == 1)
4826 VisitedRegs.
insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4829 dbgs() <<
".\n Regs:";
for (
const SCEV *S
4834 SolutionCost = NewCost;
4835 Solution = Workspace;
4847 SolutionCost.Lose();
4851 Workspace.
reserve(Uses.size());
4854 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4855 CurRegs, VisitedRegs);
4856 if (Solution.
empty()) {
4863 "The chosen solution requires ";
4864 SolutionCost.print(
dbgs());
dbgs() <<
":\n";
4865 for (
size_t i = 0, e = Uses.size(); i != e; ++i) {
4867 Uses[i].print(
dbgs());
4870 Solution[i]->print(
dbgs());
4874 assert(Solution.
size() == Uses.size() &&
"Malformed solution!");
4886 bool AllDominate =
true;
4890 if (isa<CatchSwitchInst>(Tentative))
4894 if (Inst == Tentative || !DT.
dominates(Inst, Tentative)) {
4895 AllDominate =
false;
4901 (!BetterPos || !DT.
dominates(Inst, BetterPos)))
4911 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4912 unsigned IPLoopDepth = IPLoop ? IPLoop->
getLoopDepth() : 0;
4916 if (!Rung)
return IP;
4917 Rung = Rung->getIDom();
4918 if (!Rung)
return IP;
4919 IDom = Rung->getBlock();
4922 const Loop *IDomLoop = LI.getLoopFor(IDom);
4923 unsigned IDomDepth = IDomLoop ? IDomLoop->
getLoopDepth() : 0;
4924 if (IDomDepth <= IPLoopDepth &&
4925 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4946 if (
Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4948 if (LU.Kind == LSRUse::ICmpZero)
4950 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4952 if (LF.PostIncLoops.count(L)) {
4953 if (LF.isUseFullyOutsideLoop(L))
4960 for (
const Loop *PIL : LF.PostIncLoops) {
4961 if (PIL == L)
continue;
4966 if (!ExitingBlocks.
empty()) {
4968 for (
unsigned i = 1, e = ExitingBlocks.
size(); i != e; ++i)
4974 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
4975 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4976 "Insertion point must be a normal instruction");
4983 while (isa<PHINode>(IP)) ++IP;
4986 while (IP->isEHPad()) ++IP;
4989 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
5002 Value *LSRInstance::Expand(
const LSRUse &LU,
const LSRFixup &LF,
5006 if (LU.RigidFormula)
5007 return LF.OperandValToReplace;
5011 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
5019 Type *OpTy = LF.OperandValToReplace->getType();
5021 Type *Ty = F.getType();
5035 for (
const SCEV *Reg : F.BaseRegs) {
5036 assert(!Reg->
isZero() &&
"Zero allocated in a base register!");
5044 Value *ICmpScaledV =
nullptr;
5046 const SCEV *ScaledS = F.ScaledReg;
5052 if (LU.Kind == LSRUse::ICmpZero) {
5062 "The only scale supported by ICmpZero uses is -1!");
5105 int64_t
Offset = (uint64_t)F.BaseOffset + LF.Offset;
5107 if (LU.Kind == LSRUse::ICmpZero) {
5124 int64_t UnfoldedOffset = F.UnfoldedOffset;
5125 if (UnfoldedOffset != 0) {
5143 if (LU.Kind == LSRUse::ICmpZero) {
5144 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
5146 assert(!F.BaseGV &&
"ICmp does not support folding a global value and " 5147 "a scale at the same time!");
5148 if (F.Scale == -1) {
5149 if (ICmpScaledV->
getType() != OpTy) {
5153 ICmpScaledV, OpTy,
"tmp", CI);
5160 assert((F.Scale == 0 || F.Scale == 1) &&
5161 "ICmp does not support folding a global value and " 5162 "a scale at the same time!");
5180 void LSRInstance::RewriteForPHI(
5181 PHINode *PN,
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
5196 Loop *PNLoop = LI.getLoopFor(Parent);
5197 if (!PNLoop || Parent != PNLoop->
getHeader()) {
5203 .setMergeIdenticalEdges()
5204 .setDontDeleteUselessPHIs());
5228 std::pair<DenseMap<BasicBlock *, Value *>::iterator,
bool> Pair =
5229 Inserted.
insert(std::make_pair(BB, static_cast<Value *>(
nullptr)));
5237 Type *OpTy = LF.OperandValToReplace->getType();
5242 FullV, LF.OperandValToReplace->getType(),
5246 Pair.first->second = FullV;
5254 void LSRInstance::Rewrite(
const LSRUse &LU,
const LSRFixup &LF,
5259 if (
PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
5260 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
5263 Expand(LU, LF, F, LF.UserInst->getIterator(),
Rewriter, DeadInsts);
5266 Type *OpTy = LF.OperandValToReplace->getType();
5267 if (FullV->
getType() != OpTy) {
5270 FullV, OpTy,
"tmp", LF.UserInst);
5279 if (LU.Kind == LSRUse::ICmpZero)
5280 LF.UserInst->setOperand(0, FullV);
5282 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5290 void LSRInstance::ImplementSolution(
5306 for (
const IVChain &Chain : IVChainVec) {
5307 if (
PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
5312 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5313 for (
const LSRFixup &Fixup : Uses[LUIdx].
Fixups) {
5314 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5318 for (
const IVChain &Chain : IVChainVec) {
5319 GenerateIVChain(Chain, Rewriter, DeadInsts);
5332 : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L) {
5338 if (IU.
empty())
return;
5342 unsigned NumUsers = 0;
5344 if (++NumUsers > MaxIVUsers) {
5346 LLVM_DEBUG(
dbgs() <<
"LSR skipping loop, too many IV Users in " << U
5353 if (
auto *PN = dyn_cast<PHINode>(U.getUser())) {
5355 if (isa<FuncletPadInst>(FirstNonPHI) ||
5356 isa<CatchSwitchInst>(FirstNonPHI))
5358 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5371 Rung; Rung = Rung->
getIDom()) {
5374 if (DomLoop && DomLoop->
getHeader() == BB) {
5386 OptimizeLoopTermCond();
5389 if (IU.empty())
return;
5399 CollectInterestingTypesAndFactors();
5400 CollectFixupsAndInitialFormulae();
5401 CollectLoopInvariantFixupsAndFormulae();
5407 print_uses(
dbgs()));
5411 GenerateAllReuseFormulae();
5413 FilterOutUndesirableDedicatedRegisters();
5414 NarrowSearchSpaceUsingHeuristics();
5424 if (Solution.
empty())
5429 for (
const LSRUse &LU : Uses) {
5430 for (
const Formula &F : LU.Formulae)
5432 F) &&
"Illegal formula generated!");
5437 ImplementSolution(Solution);
5440 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 5441 void LSRInstance::print_factors_and_types(
raw_ostream &OS)
const {
5442 if (Factors.empty() && Types.empty())
return;
5444 OS <<
"LSR has identified the following interesting factors and types: ";
5447 for (int64_t Factor : Factors) {
5448 if (!First) OS <<
", ";
5450 OS <<
'*' << Factor;
5453 for (
Type *Ty : Types) {
5454 if (!First) OS <<
", ";
5456 OS <<
'(' << *Ty <<
')';
5461 void LSRInstance::print_fixups(
raw_ostream &OS)
const {
5462 OS <<
"LSR is examining the following fixup sites:\n";
5463 for (
const LSRUse &LU : Uses)
5464 for (
const LSRFixup &LF : LU.Fixups) {
5471 void LSRInstance::print_uses(
raw_ostream &OS)
const {
5472 OS <<
"LSR is examining the following uses:\n";
5473 for (
const LSRUse &LU : Uses) {
5477 for (
const Formula &F : LU.Formulae) {
5486 print_factors_and_types(OS);
5498 class LoopStrengthReduce :
public LoopPass {
5502 LoopStrengthReduce();
5511 LoopStrengthReduce::LoopStrengthReduce() :
LoopPass(
ID) {
5515 void LoopStrengthReduce::getAnalysisUsage(
AnalysisUsage &AU)
const {
5538 bool Changed =
false;
5541 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged();
5566 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5567 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5568 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5569 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5570 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5588 "Loop Strength Reduction",
false,
false)
Pass interface - Implemented by all 'passes'.
static bool isValueValidForType(Type *Ty, uint64_t V)
This static method returns true if the type Ty is big enough to represent the value V...
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. ...
const_iterator end(StringRef path)
Get end iterator over path.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
iterator_range< use_iterator > uses()
AnalysisUsage & addPreserved()
Add the specified Pass class to the set of analyses preserved by this pass.
raw_ostream & errs()
This returns a reference to a raw_ostream for standard error.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
const_iterator begin(StringRef path, Style style=Style::native)
Get begin iterator over path.
DiagnosticInfoOptimizationBase::Argument NV
typename SuperClass::const_iterator const_iterator
static bool isExistingPhi(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Return true if this AddRec is already a phi in its loop.
Pass * createLoopStrengthReducePass()
This is a 'bitvector' (really, a variable-sized bit array), optimized for the case when the array is ...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs... ExtraArgs)
Get the result of an analysis pass for a given IR unit.
const SCEV * getConstant(ConstantInt *V)
Compute iterated dominance frontiers using a linear time algorithm.
size_type size() const
Determine the number of elements in the SetVector.
Type * getEffectiveSCEVType(Type *Ty) const
Return a type with the same bitwidth as the given type and which represents how SCEV will treat the g...
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
an instruction that atomically checks whether a specified value is in a memory location, and, if it is, stores a new value there.
const SCEV * normalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Normalize S to be post-increment for all loops present in Loops.
static const size_t ComplexityLimit
size_t getNumOperands() const
Implements a dense probed hash-table based set.
unsigned getLoopDepth() const
Return the nesting level of this loop.
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
The main scalar evolution driver.
bool isZero() const
Return true if the expression is a constant zero.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
static const unsigned MaxIVUsers
MaxIVUsers is an arbitrary threshold that provides an early opportunity for bail out.
bool properlyDominates(const SCEV *S, const BasicBlock *BB)
Return true if elements that makes up the given SCEV properly dominate the specified basic block...
void initializeLoopStrengthReducePass(PassRegistry &)
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
void setDebugType(const char *s)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
void resize(unsigned N, bool t=false)
Grow or shrink the bitvector.
static void dump(StringRef Title, SpillInfo const &Spills)
bool properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
An instruction for reading from memory.
an instruction that atomically reads a memory location, combines it with another value, and then stores the result back.
Value * getCondition() const
iv Induction Variable Users
This defines the Use class.
void reserve(size_type N)
bool hasNoSignedWrap() const
iterator end()
Get an iterator to the end of the SetVector.
INITIALIZE_PASS_BEGIN(LoopStrengthReduce, "loop-reduce", "Loop Strength Reduction", false, false) INITIALIZE_PASS_END(LoopStrengthReduce
This is the base class for unary cast operator classes.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
SI optimize exec mask operations pre RA
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
static cl::opt< bool > InsnsCost("lsr-insns-cost", cl::Hidden, cl::init(true), cl::desc("Add instruction count to a LSR cost model"))
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
Option class for critical edge splitting.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
void clearPostInc()
Disable all post-inc expansion.
A Use represents the edge between a Value definition and its users.
static User::op_iterator findIVOperand(User::op_iterator OI, User::op_iterator OE, Loop *L, ScalarEvolution &SE)
Helper for CollectChains that finds an IV operand (computed by an AddRec in this loop) within [OI...
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
LLVMContext & getContext() const
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
void setName(const Twine &Name)
Change the name of the value.
This node represents multiplication of some number of SCEVs.
This file implements a class to represent arbitrary precision integral constant values and operations...
const APInt & getAPInt() const
BlockT * getHeader() const
ConstantInt * getValue() const
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
Type * getType() const
All values are typed, get the type of this value.
bool insert(const value_type &X)
Insert a new element into the SetVector.
static bool isEqual(const Function &Caller, const Function &Callee)
This node represents a polynomial recurrence on the trip count of the specified loop.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
iterator_range< const_set_bits_iterator > set_bits() const
This header provides classes for managing per-loop analyses.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
AnalysisUsage & addPreservedID(const void *ID)
An instruction for storing to memory.
op_iterator op_begin() const
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
int getFPMantissaWidth() const
Return the width of the mantissa of this type.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock *> Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock *> &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
This class represents a truncation of integer types.
const SCEV * getAddRecExpr(const SCEV *Start, const SCEV *Step, const Loop *L, SCEV::NoWrapFlags Flags)
Get an add recurrence expression for the specified loop.
Value * getOperand(unsigned i) const
Class to represent pointers.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(adl_begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
static bool DeleteTriviallyDeadInstructions(SmallVectorImpl< WeakTrackingVH > &DeadInsts)
If any of the instructions in the specified set are trivially dead, delete them and see if this makes...
iterator find(const_arg_type_t< KeyT > Val)
Value * getOperand(unsigned i_nocapture) const
static cl::opt< bool > FilterSameScaledReg("lsr-filter-same-scaled-reg", cl::Hidden, cl::init(true), cl::desc("Narrow LSR search space by filtering non-optimal formulae" " with the same ScaledReg and Scale"))
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
static bool isCompatibleIVType(Value *LVal, Value *RVal)
Return true if we allow an IV chain to include both types.
static bool isAddressUse(const TargetTransformInfo &TTI, Instruction *Inst, Value *OperandVal)
Returns true if the specified instruction is using the specified value as an address.
This means that we are dealing with an entirely unknown SCEV value, and only represent it as its LLVM...
initializer< Ty > init(const Ty &Val)
const SCEV * getOperand(unsigned i) const
bool isAllOnesValue() const
Determine if all bits are set.
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
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")
void dump(const SparseBitVector< ElementSize > &LHS, raw_ostream &out)
A set of analyses that are preserved following a run of a transformation pass.
void setUser(Instruction *NewUser)
setUser - Assign a new user instruction for this use.
* if(!EatIfPresent(lltok::kw_thread_local)) return false
ParseOptionalThreadLocal := /*empty.
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
static bool isLegalUse(const TargetTransformInfo &TTI, int64_t MinOffset, int64_t MaxOffset, LSRUse::KindType Kind, MemAccessTy AccessTy, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg, int64_t Scale)
Test whether we know how to expand the current formula.
static bool isMulSExtable(const SCEVMulExpr *M, ScalarEvolution &SE)
Return true if the given mul can be sign-extended without changing its value.
LLVM Basic Block Representation.
PointerIntPair - This class implements a pair of a pointer and small integer.
This class represents a binary unsigned division operation.
The instances of the Type class are immutable: once they are created, they are never changed...
This is an important class for using LLVM in a threaded context.
void setInsertPoint(Instruction *IP)
Set the current insertion point.
Conditional or Unconditional Branch instruction.
static bool isProfitableChain(IVChain &Chain, SmallPtrSetImpl< Instruction *> &Users, ScalarEvolution &SE, const TargetTransformInfo &TTI)
Return true if the number of registers needed for the chain is estimated to be less than the number r...
DomTreeNodeBase * getIDom() const
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
This is an important base class in LLVM.
LLVM_NODISCARD bool empty() const
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
static const unsigned UnknownAddressSpace
std::pair< iterator, bool > insert(const ValueT &V)
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
static cl::opt< bool > EnablePhiElim("enable-lsr-phielim", cl::Hidden, cl::init(true), cl::desc("Enable LSR phi elimination"))
bool isMinSignedValue() const
Determine if this is the smallest signed value.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
static bool isAlwaysFoldable(const TargetTransformInfo &TTI, LSRUse::KindType Kind, MemAccessTy AccessTy, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg)
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
op_iterator op_end() const
static int64_t ExtractImmediate(const SCEV *&S, ScalarEvolution &SE)
If S involves the addition of a constant integer value, return that integer value, and mutate S to point to a new SCEV with that value excluded.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
static void print(raw_ostream &Out, object::Archive::Kind Kind, T Val)
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
self_iterator getIterator()
iterator_range< block_iterator > blocks()
const SCEV * getStart() const
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
auto find_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
const SCEV * getMinusSCEV(const SCEV *LHS, const SCEV *RHS, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Return LHS-RHS. Minus is represented in SCEV as A+B*-1.
static Constant * getAllOnesValue(Type *Ty)
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
static const SCEV * CollectSubexprs(const SCEV *S, const SCEVConstant *C, SmallVectorImpl< const SCEV *> &Ops, const Loop *L, ScalarEvolution &SE, unsigned Depth=0)
Split S into subexpressions which can be pulled out into separate registers.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static unsigned getIncomingValueNumForOperand(unsigned i)
static wasm::ValType getType(const TargetRegisterClass *RC)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
DomTreeNodeBase< NodeT > * getNode(const NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
auto find(R &&Range, const T &Val) -> decltype(adl_begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
const SCEV * getMulExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical multiply expression, or something simpler if possible.
void printAsOperand(raw_ostream &O, bool PrintType=true, const Module *M=nullptr) const
Print the name of this Value out to the specified raw_ostream.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE)
Return true if the given add can be sign-extended without changing its value.
TargetTransformInfo & TTI
void sort(IteratorTy Start, IteratorTy End)
void setChainedPhi(PHINode *PN)
PowerPC TLS Dynamic Call Fixup
static const SCEV * getExactSDiv(const SCEV *LHS, const SCEV *RHS, ScalarEvolution &SE, bool IgnoreSignificantBits=false)
Return an expression for LHS /s RHS, if it can be determined and if the remainder is known to be zero...
bool isLandingPad() const
Return true if this basic block is a landing pad.
iterator_range< T > make_range(T x, T y)
Convenience function for iterating over sub-ranges.
This class provides an interface for updating the loop pass manager based on mutations to the loop ne...
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
unsigned getSCEVType() const
A SetVector that performs no allocations if smaller than a certain size.
Iterator for intrusive lists based on ilist_node.
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
static cl::opt< bool > StressIVChain("stress-ivchain", cl::Hidden, cl::init(false), cl::desc("Stress test LSR IV chains"))
unsigned getScalarSizeInBits() const LLVM_READONLY
If this is a vector type, return the getPrimitiveSizeInBits value for the element type...
AnalysisUsage & addRequiredID(const void *ID)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
void setIVIncInsertPos(const Loop *L, Instruction *Pos)
Set the current IV increment loop and position.
static Value * getWideOperand(Value *Oper)
IVChain logic must consistently peek base TruncInst operands, so wrap it in a convenient helper...
LLVM_NODISCARD T pop_back_val()
CHAIN = SC CHAIN, Imm128 - System call.
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 ConstantInt * getSigned(IntegerType *Ty, int64_t V)
Return a ConstantInt with the specified value for the specified type.
size_t size() const
Returns the number of bits in this bitvector.
static bool isAMCompletelyFolded(const TargetTransformInfo &TTI, const LSRUse &LU, const Formula &F)
Check if the addressing mode defined by F is completely folded in LU at isel time.
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
static Constant * get(Type *Ty, double V)
This returns a ConstantFP, or a vector containing a splat of a ConstantFP, for the specified value in...
unsigned getNumIncomingValues() const
Return the number of incoming edges.
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
unsigned Log2_32(uint32_t Value)
Return the floor log base 2 of the specified value, -1 if the value is zero.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
static void DoInitialMatch(const SCEV *S, Loop *L, SmallVectorImpl< const SCEV *> &Good, SmallVectorImpl< const SCEV *> &Bad, ScalarEvolution &SE)
Recursion helper for initialMatch.
bool isTrueWhenEqual() const
This is just a convenience.
Class for arbitrary precision integers.
This node represents an addition of some number of SCEVs.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
This class represents a signed maximum selection.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
This class uses information about analyze scalars to rewrite expressions in canonical form...
static Constant * getCast(unsigned ops, Constant *C, Type *Ty, bool OnlyIfReduced=false)
Convenience function for getting a Cast operation.
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
static void clear(coro::Shape &Shape)
loop Loop Strength Reduction
iterator insert(iterator I, T &&Elt)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
virtual bool runOnLoop(Loop *L, LPPassManager &LPM)=0
Virtual Register Rewriter
bool operator!=(uint64_t V1, const APInt &V2)
static CastInst * Create(Instruction::CastOps, Value *S, Type *Ty, const Twine &Name="", Instruction *InsertBefore=nullptr)
Provides a way to construct any of the CastInst subclasses using an opcode instead of the subclass's ...
Predicate getPredicate() const
Return the predicate for this instruction.
static bool mayUsePostIncMode(const TargetTransformInfo &TTI, LSRUse &LU, const SCEV *S, const Loop *L, ScalarEvolution &SE)
Return true if the SCEV represents a value that may end up as a post-increment operation.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
static unsigned getScalingFactorCost(const TargetTransformInfo &TTI, const LSRUse &LU, const Formula &F, const Loop &L)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
void emplace_back(ArgTypes &&... Args)
This class represents an analyzed expression in the program.
Analysis pass that exposes the IVUsers for a loop.
bool hasNoUnsignedWrap() const
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
Value * getOperandValToReplace() const
getOperandValToReplace - Return the Value of the operand in the user instruction that this IVStrideUs...
static Instruction::CastOps getCastOpcode(const Value *Val, bool SrcIsSigned, Type *Ty, bool DstIsSigned)
Returns the opcode necessary to cast Val into Ty using usual casting rules.
static const SCEV * getExprBase(const SCEV *S)
Return an approximation of this SCEV expression's "base", or NULL for any constant.
APFloat abs(APFloat X)
Returns the absolute value of the argument.
Sequence
A sequence of states that a pointer may go through in which an objc_retain and objc_release are actua...
This class represents a cast unsigned integer to floating point.
static MemAccessTy getAccessType(const TargetTransformInfo &TTI, Instruction *Inst, Value *OperandVal)
Return the type of the memory being accessed.
This class represents an unsigned maximum selection.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
bool isUnconditional() const
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
void transformToPostInc(const Loop *L)
transformToPostInc - Transform the expression to post-inc form for the given loop.
static bool canFoldIVIncExpr(const SCEV *IncExpr, Instruction *UserInst, Value *Operand, const TargetTransformInfo &TTI)
Return true if the IVInc can be folded into an addressing mode.
static cl::opt< bool > LSRExpNarrow("lsr-exp-narrow", cl::Hidden, cl::init(false), cl::desc("Narrow LSR complex solution using" " expectation of registers number"))
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
This class represents a cast from signed integer to floating point.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
const SCEV * denormalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Denormalize S to be post-increment for all loops present in Loops.
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.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
static GlobalValue * ExtractSymbol(const SCEV *&S, ScalarEvolution &SE)
If S involves the addition of a GlobalValue address, return that symbol, and mutate S to point to a n...
A vector that has set insertion semantics.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
IVStrideUse - Keep track of one use of a strided induction variable.
This class implements an extremely fast bulk output stream that can only output to a stream...
void disableCanonicalMode()
Disable the behavior of expanding expressions in canonical form rather than in a more literal form...
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
const SCEV * getUnknown(Value *V)
The legacy pass manager's analysis pass to compute loop information.
Value * PtrVal
This is the pointer that the intrinsic is loading from or storing to.
bool hasOneUse() const
Return true if there is exactly one user of this value.
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
bool operator==(uint64_t V1, const APInt &V2)
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
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...
bool hasComputableLoopEvolution(const SCEV *S, const Loop *L)
Return true if the given SCEV changes value in a known way in the specified loop. ...
This node is a base class providing common functionality for n'ary operators.
This header defines various interfaces for pass management in LLVM.
void setIncomingValue(unsigned i, Value *V)
for(unsigned i=Desc.getNumOperands(), e=OldMI.getNumOperands();i !=e;++i)
void setPostInc(const PostIncLoopSet &L)
Enable post-inc expansion for addrecs referring to the given loops.
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, LoopInfo &LI, const TargetTransformInfo &TTI)
Information about a load/store intrinsic defined by the target.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
size_type count() const
Returns the number of bits which are set.
static bool isHighCostExpansion(const SCEV *S, SmallPtrSetImpl< const SCEV *> &Processed, ScalarEvolution &SE)
Check if expanding this expression is likely to incur significant cost.
static bool isAddRecSExtable(const SCEVAddRecExpr *AR, ScalarEvolution &SE)
Return true if the given addrec can be sign-extended without changing its value.
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
A wrapper class for inspecting calls to intrinsic functions.
const BasicBlock * getParent() const
This class represents a constant integer value.
const SCEV * getAnyExtendExpr(const SCEV *Op, Type *Ty)
getAnyExtendExpr - Return a SCEV for the given operand extended with unspecified bits out to the give...
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.