77 #include "llvm/Config/llvm-config.h" 123 using namespace llvm;
125 #define DEBUG_TYPE "loop-reduce" 139 cl::desc(
"Enable LSR phi elimination"));
144 cl::desc(
"Add instruction count to a LSR cost model"));
149 cl::desc(
"Narrow LSR complex solution using" 150 " expectation of registers number"));
156 cl::desc(
"Narrow LSR search space by filtering non-optimal formulae" 157 " with the same ScaledReg and Scale"));
161 cl::desc(
"Enable the generation of cross iteration indexed memops"));
166 cl::desc(
"LSR search space complexity limit"));
170 cl::desc(
"The limit on recursion depth for LSRs setup cost"));
176 cl::desc(
"Stress test LSR IV chains"));
188 Type *MemTy =
nullptr;
191 MemAccessTy() =
default;
192 MemAccessTy(
Type *Ty,
unsigned AS) : MemTy(Ty), AddrSpace(AS) {}
195 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
201 unsigned AS = UnknownAddressSpace) {
221 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 223 OS <<
"[NumUses=" << UsedByIndices.count() <<
']';
234 class RegUseTracker {
237 RegUsesTy RegUsesMap;
241 void countRegister(
const SCEV *
Reg,
size_t LUIdx);
242 void dropRegister(
const SCEV *
Reg,
size_t LUIdx);
243 void swapAndDropUse(
size_t LUIdx,
size_t LastLUIdx);
245 bool isRegUsedByUsesOtherThan(
const SCEV *
Reg,
size_t LUIdx)
const;
254 iterator
begin() {
return RegSequence.
begin(); }
255 iterator
end() {
return RegSequence.
end(); }
256 const_iterator
begin()
const {
return RegSequence.
begin(); }
257 const_iterator
end()
const {
return RegSequence.
end(); }
263 RegUseTracker::countRegister(
const SCEV *
Reg,
size_t LUIdx) {
264 std::pair<RegUsesTy::iterator, bool> Pair =
265 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
266 RegSortData &RSD = Pair.first->second;
269 RSD.UsedByIndices.resize(
std::max(RSD.UsedByIndices.size(), LUIdx + 1));
270 RSD.UsedByIndices.set(LUIdx);
274 RegUseTracker::dropRegister(
const SCEV *Reg,
size_t LUIdx) {
275 RegUsesTy::iterator It = RegUsesMap.find(Reg);
276 assert(It != RegUsesMap.end());
277 RegSortData &RSD = It->second;
278 assert(RSD.UsedByIndices.size() > LUIdx);
279 RSD.UsedByIndices.reset(LUIdx);
283 RegUseTracker::swapAndDropUse(
size_t LUIdx,
size_t LastLUIdx) {
284 assert(LUIdx <= LastLUIdx);
288 for (
auto &Pair : RegUsesMap) {
290 if (LUIdx < UsedByIndices.
size())
291 UsedByIndices[LUIdx] =
292 LastLUIdx < UsedByIndices.
size() ? UsedByIndices[LastLUIdx] :
false;
293 UsedByIndices.
resize(std::min(UsedByIndices.
size(), LastLUIdx));
298 RegUseTracker::isRegUsedByUsesOtherThan(
const SCEV *Reg,
size_t LUIdx)
const {
299 RegUsesTy::const_iterator
I = RegUsesMap.find(Reg);
300 if (I == RegUsesMap.end())
304 if (i == -1)
return false;
305 if ((
size_t)i != LUIdx)
return true;
310 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
311 assert(I != RegUsesMap.end() &&
"Unknown register!");
312 return I->second.UsedByIndices;
329 int64_t BaseOffset = 0;
332 bool HasBaseReg =
false;
355 const SCEV *ScaledReg =
nullptr;
360 int64_t UnfoldedOffset = 0;
368 void canonicalize(
const Loop &L);
372 bool hasZeroEnd()
const;
374 size_t getNumRegs()
const;
377 void deleteBaseReg(
const SCEV *&S);
379 bool referencesReg(
const SCEV *S)
const;
380 bool hasRegsUsedByUsesOtherThan(
size_t LUIdx,
381 const RegUseTracker &RegUses)
const;
402 for (
const SCEV *S :
Add->operands())
409 if (!AR->getStart()->isZero() && AR->isAffine()) {
412 AR->getStepRecurrence(SE),
420 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
421 if (Mul->getOperand(0)->isAllOnesValue()) {
430 for (
const SCEV *S : MyGood)
432 for (
const SCEV *S : MyBad)
451 BaseRegs.push_back(Sum);
457 BaseRegs.push_back(Sum);
468 return BaseRegs.size() <= 1;
473 if (Scale == 1 && BaseRegs.empty())
477 if (SAR && SAR->
getLoop() == &L)
485 return isa<const SCEVAddRecExpr>(S) &&
486 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
488 return I == BaseRegs.end();
497 void Formula::canonicalize(
const Loop &L) {
502 assert(!BaseRegs.empty() &&
"1*reg => reg, should not be needed.");
506 ScaledReg = BaseRegs.back();
515 if (!SAR || SAR->
getLoop() != &L) {
518 return isa<const SCEVAddRecExpr>(S) &&
519 (cast<SCEVAddRecExpr>(S)->getLoop() == &L);
521 if (I != BaseRegs.end())
530 bool Formula::unscale() {
534 BaseRegs.push_back(ScaledReg);
539 bool Formula::hasZeroEnd()
const {
540 if (UnfoldedOffset || BaseOffset)
542 if (BaseRegs.size() != 1 || ScaledReg)
549 size_t Formula::getNumRegs()
const {
550 return !!ScaledReg + BaseRegs.size();
556 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
557 ScaledReg ? ScaledReg->getType() :
558 BaseGV ? BaseGV->getType() :
563 void Formula::deleteBaseReg(
const SCEV *&S) {
564 if (&S != &BaseRegs.back())
570 bool Formula::referencesReg(
const SCEV *S)
const {
576 bool Formula::hasRegsUsedByUsesOtherThan(
size_t LUIdx,
577 const RegUseTracker &RegUses)
const {
579 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
581 for (
const SCEV *BaseReg : BaseRegs)
582 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
587 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 591 if (!First) OS <<
" + ";
else First =
false;
592 BaseGV->printAsOperand(OS,
false);
594 if (BaseOffset != 0) {
595 if (!First) OS <<
" + ";
else First =
false;
598 for (
const SCEV *BaseReg : BaseRegs) {
599 if (!First) OS <<
" + ";
else First =
false;
600 OS <<
"reg(" << *BaseReg <<
')';
602 if (HasBaseReg && BaseRegs.empty()) {
603 if (!First) OS <<
" + ";
else First =
false;
604 OS <<
"**error: HasBaseReg**";
605 }
else if (!HasBaseReg && !BaseRegs.empty()) {
606 if (!First) OS <<
" + ";
else First =
false;
607 OS <<
"**error: !HasBaseReg**";
610 if (!First) OS <<
" + ";
else First =
false;
611 OS << Scale <<
"*reg(";
618 if (UnfoldedOffset != 0) {
619 if (!First) OS <<
" + ";
620 OS <<
"imm(" << UnfoldedOffset <<
')';
661 bool IgnoreSignificantBits =
false) {
683 const APInt &LA =
C->getAPInt();
685 if (LA.
srem(RA) != 0)
692 if ((IgnoreSignificantBits ||
isAddRecSExtable(AR, SE)) && AR->isAffine()) {
694 IgnoreSignificantBits);
695 if (!Step)
return nullptr;
697 IgnoreSignificantBits);
698 if (!Start)
return nullptr;
711 for (
const SCEV *S :
Add->operands()) {
713 if (!Op)
return nullptr;
722 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
726 for (
const SCEV *S : Mul->operands()) {
729 IgnoreSignificantBits)) {
748 if (
C->getAPInt().getMinSignedBits() <= 64) {
750 return C->getValue()->getSExtValue();
758 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
773 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
774 if (
GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
784 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
800 bool isAddress = isa<LoadInst>(Inst);
802 if (
SI->getPointerOperand() == OperandVal)
804 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
807 switch (II->getIntrinsicID()) {
808 case Intrinsic::memset:
810 if (II->getArgOperand(0) == OperandVal)
813 case Intrinsic::memmove:
814 case Intrinsic::memcpy:
815 if (II->getArgOperand(0) == OperandVal ||
816 II->getArgOperand(1) == OperandVal)
822 if (IntrInfo.
PtrVal == OperandVal)
827 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
828 if (RMW->getPointerOperand() == OperandVal)
831 if (CmpX->getPointerOperand() == OperandVal)
841 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
842 AccessTy.MemTy =
SI->getOperand(0)->getType();
843 AccessTy.AddrSpace =
SI->getPointerAddressSpace();
844 }
else if (
const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
845 AccessTy.AddrSpace = LI->getPointerAddressSpace();
846 }
else if (
const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
847 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
849 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
850 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
851 switch (II->getIntrinsicID()) {
853 case Intrinsic::memset:
854 AccessTy.AddrSpace = II->getArgOperand(0)->getType()->getPointerAddressSpace();
855 AccessTy.MemTy = OperandVal->
getType();
857 case Intrinsic::memmove:
858 case Intrinsic::memcpy:
860 AccessTy.MemTy = OperandVal->
getType();
876 if (
PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
878 PTy->getAddressSpace());
923 if (!Processed.
insert(S).second)
927 for (
const SCEV *S :
Add->operands()) {
934 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
935 if (Mul->getNumOperands() == 2) {
937 if (isa<SCEVConstant>(Mul->getOperand(0)))
942 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
943 Value *UVal = U->getValue();
947 if (UI && UI->
getOpcode() == Instruction::Mul &&
969 bool Changed =
false;
971 while (!DeadInsts.
empty()) {
1008 const LSRUse &LU,
const Formula &
F);
1012 const LSRUse &LU,
const Formula &F,
1019 const Loop *L =
nullptr;
1027 L(L), SE(&SE), TTI(&TTI) {
1038 bool isLess(Cost &
Other);
1053 assert(isValid() &&
"invalid cost");
1057 void RateFormula(
const Formula &F,
1067 void RateRegister(
const Formula &F,
const SCEV *Reg,
1069 void RatePrimaryRegister(
const Formula &F,
const SCEV *Reg,
1082 Value *OperandValToReplace =
nullptr;
1094 LSRFixup() =
default;
1096 bool isUseFullyOutsideLoop(
const Loop *L)
const;
1104 struct UniquifierDenseMapInfo {
1107 V.
push_back(reinterpret_cast<const SCEV *>(-1));
1113 V.
push_back(reinterpret_cast<const SCEV *>(-2));
1149 MemAccessTy AccessTy;
1156 int64_t MaxOffset = std::numeric_limits<int64_t>::min();
1160 bool AllFixupsOutsideLoop =
true;
1167 bool RigidFormula =
false;
1173 Type *WidestFixupType =
nullptr;
1183 LSRUse(KindType K, MemAccessTy AT) :
Kind(K), AccessTy(AT) {}
1185 LSRFixup &getNewFixup() {
1187 return Fixups.
back();
1190 void pushFixup(LSRFixup &f) {
1192 if (f.Offset > MaxOffset)
1193 MaxOffset = f.Offset;
1194 if (f.Offset < MinOffset)
1195 MinOffset = f.Offset;
1198 bool HasFormulaWithSameRegs(
const Formula &F)
const;
1199 float getNotSelectedProbability(
const SCEV *Reg)
const;
1200 bool InsertFormula(
const Formula &F,
const Loop &L);
1201 void DeleteFormula(Formula &F);
1202 void RecomputeRegs(
size_t LUIdx, RegUseTracker &Reguses);
1211 LSRUse::KindType
Kind, MemAccessTy AccessTy,
1213 bool HasBaseReg, int64_t Scale,
1217 if (isa<SCEVUnknown>(Reg) || isa<SCEVConstant>(Reg))
1221 if (
const auto *S = dyn_cast<SCEVAddRecExpr>(Reg))
1223 if (
auto S = dyn_cast<SCEVCastExpr>(Reg))
1225 if (
auto S = dyn_cast<SCEVNAryExpr>(Reg))
1226 return std::accumulate(S->op_begin(), S->op_end(), 0,
1227 [&](
unsigned i,
const SCEV *
Reg) {
1230 if (
auto S = dyn_cast<SCEVUDivExpr>(Reg))
1237 void Cost::RateRegister(
const Formula &F,
const SCEV *Reg,
1243 if (AR->getLoop() != L) {
1250 if (!AR->getLoop()->contains(L)) {
1260 unsigned LoopCost = 1;
1267 if (
auto *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE)))
1268 if (Step->getAPInt() == F.BaseOffset)
1273 const SCEV *LoopStep = AR->getStepRecurrence(*SE);
1274 if (isa<SCEVConstant>(LoopStep)) {
1275 const SCEV *LoopStart = AR->getStart();
1276 if (!isa<SCEVConstant>(LoopStart) &&
1282 C.AddRecCost += LoopCost;
1286 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1287 if (!Regs.
count(AR->getOperand(1))) {
1288 RateRegister(F, AR->getOperand(1), Regs);
1300 C.SetupCost = std::min<unsigned>(
C.SetupCost, 1 << 16);
1302 C.NumIVMuls += isa<SCEVMulExpr>(
Reg) &&
1309 void Cost::RatePrimaryRegister(
const Formula &F,
const SCEV *Reg,
1312 if (LoserRegs && LoserRegs->
count(Reg)) {
1316 if (Regs.
insert(Reg).second) {
1317 RateRegister(F, Reg, Regs);
1318 if (LoserRegs && isLoser())
1323 void Cost::RateFormula(
const Formula &F,
1328 assert(F.isCanonical(*L) &&
"Cost is accurate only for canonical formula");
1330 unsigned PrevAddRecCost =
C.AddRecCost;
1331 unsigned PrevNumRegs =
C.NumRegs;
1332 unsigned PrevNumBaseAdds =
C.NumBaseAdds;
1333 if (
const SCEV *ScaledReg = F.ScaledReg) {
1334 if (VisitedRegs.
count(ScaledReg)) {
1338 RatePrimaryRegister(F, ScaledReg, Regs, LoserRegs);
1342 for (
const SCEV *BaseReg : F.BaseRegs) {
1343 if (VisitedRegs.
count(BaseReg)) {
1347 RatePrimaryRegister(F, BaseReg, Regs, LoserRegs);
1353 size_t NumBaseParts = F.getNumRegs();
1354 if (NumBaseParts > 1)
1359 C.NumBaseAdds += (F.UnfoldedOffset != 0);
1365 for (
const LSRFixup &
Fixup : LU.Fixups) {
1366 int64_t
O = Fixup.Offset;
1367 int64_t
Offset = (uint64_t)O + F.BaseOffset;
1371 else if (Offset != 0)
1378 Offset, F.HasBaseReg, F.Scale, Fixup.UserInst))
1384 assert(isValid() &&
"invalid cost");
1393 if (
C.NumRegs > TTIRegNum) {
1396 if (PrevNumRegs > TTIRegNum)
1397 C.Insns += (
C.NumRegs - PrevNumRegs);
1399 C.Insns += (
C.NumRegs - TTIRegNum);
1412 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd() &&
1416 C.Insns += (
C.AddRecCost - PrevAddRecCost);
1419 if (LU.Kind != LSRUse::ICmpZero)
1420 C.Insns +=
C.NumBaseAdds - PrevNumBaseAdds;
1421 assert(isValid() &&
"invalid cost");
1437 bool Cost::isLess(Cost &
Other) {
1439 C.Insns != Other.C.Insns)
1440 return C.Insns < Other.C.Insns;
1444 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1447 OS <<
C.Insns <<
" instruction" << (
C.Insns == 1 ?
" " :
"s ");
1448 OS <<
C.NumRegs <<
" reg" << (
C.NumRegs == 1 ?
"" :
"s");
1449 if (
C.AddRecCost != 0)
1450 OS <<
", with addrec cost " <<
C.AddRecCost;
1451 if (
C.NumIVMuls != 0)
1452 OS <<
", plus " <<
C.NumIVMuls <<
" IV mul" 1453 << (
C.NumIVMuls == 1 ?
"" :
"s");
1454 if (
C.NumBaseAdds != 0)
1455 OS <<
", plus " <<
C.NumBaseAdds <<
" base add" 1456 << (
C.NumBaseAdds == 1 ?
"" :
"s");
1457 if (
C.ScaleCost != 0)
1458 OS <<
", plus " <<
C.ScaleCost <<
" scale cost";
1460 OS <<
", plus " <<
C.ImmCost <<
" imm cost";
1461 if (
C.SetupCost != 0)
1462 OS <<
", plus " <<
C.SetupCost <<
" setup cost";
1471 bool LSRFixup::isUseFullyOutsideLoop(
const Loop *L)
const {
1473 if (
const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1474 for (
unsigned i = 0,
e = PN->getNumIncomingValues(); i !=
e; ++i)
1475 if (PN->getIncomingValue(i) == OperandValToReplace &&
1476 L->
contains(PN->getIncomingBlock(i)))
1484 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1490 Store->getOperand(0)->printAsOperand(OS,
false);
1491 }
else if (UserInst->getType()->isVoidTy())
1492 OS << UserInst->getOpcodeName();
1494 UserInst->printAsOperand(OS,
false);
1496 OS <<
", OperandValToReplace=";
1497 OperandValToReplace->printAsOperand(OS,
false);
1499 for (
const Loop *PIL : PostIncLoops) {
1500 OS <<
", PostIncLoop=";
1501 PIL->getHeader()->printAsOperand(OS,
false);
1505 OS <<
", Offset=" <<
Offset;
1515 bool LSRUse::HasFormulaWithSameRegs(
const Formula &F)
const {
1517 if (F.ScaledReg) Key.
push_back(F.ScaledReg);
1520 return Uniquifier.count(Key);
1524 float LSRUse::getNotSelectedProbability(
const SCEV *Reg)
const {
1526 for (
const Formula &F : Formulae)
1527 if (F.referencesReg(Reg))
1529 return ((
float)(Formulae.size() - FNum)) / Formulae.size();
1534 bool LSRUse::InsertFormula(
const Formula &F,
const Loop &L) {
1535 assert(F.isCanonical(L) &&
"Invalid canonical representation");
1537 if (!Formulae.empty() && RigidFormula)
1541 if (F.ScaledReg) Key.
push_back(F.ScaledReg);
1545 if (!Uniquifier.insert(Key).second)
1549 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1550 "Zero allocated in a scaled register!");
1552 for (
const SCEV *BaseReg : F.BaseRegs)
1553 assert(!BaseReg->
isZero() &&
"Zero allocated in a base register!");
1557 Formulae.push_back(F);
1560 Regs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
1562 Regs.
insert(F.ScaledReg);
1568 void LSRUse::DeleteFormula(Formula &F) {
1569 if (&F != &Formulae.back())
1571 Formulae.pop_back();
1575 void LSRUse::RecomputeRegs(
size_t LUIdx, RegUseTracker &RegUses) {
1579 for (
const Formula &F : Formulae) {
1580 if (F.ScaledReg) Regs.
insert(F.ScaledReg);
1581 Regs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
1585 for (
const SCEV *S : OldRegs)
1587 RegUses.dropRegister(S, LUIdx);
1590 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 1592 OS <<
"LSR Use: Kind=";
1594 case Basic: OS <<
"Basic";
break;
1595 case Special: OS <<
"Special";
break;
1596 case ICmpZero: OS <<
"ICmpZero";
break;
1598 OS <<
"Address of ";
1599 if (AccessTy.MemTy->isPointerTy())
1602 OS << *AccessTy.MemTy;
1605 OS <<
" in addrspace(" << AccessTy.AddrSpace <<
')';
1608 OS <<
", Offsets={";
1609 bool NeedComma =
false;
1611 if (NeedComma) OS <<
',';
1617 if (AllFixupsOutsideLoop)
1618 OS <<
", all-fixups-outside-loop";
1620 if (WidestFixupType)
1621 OS <<
", widest fixup type: " << *WidestFixupType;
1630 LSRUse::KindType Kind, MemAccessTy AccessTy,
1632 bool HasBaseReg, int64_t Scale,
1637 HasBaseReg, Scale, AccessTy.AddrSpace, Fixup);
1639 case LSRUse::ICmpZero:
1646 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1651 if (Scale != 0 && Scale != -1)
1656 if (BaseOffset != 0) {
1664 BaseOffset = -(uint64_t)BaseOffset;
1673 return !BaseGV && Scale == 0 && BaseOffset == 0;
1675 case LSRUse::Special:
1677 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1684 int64_t MinOffset, int64_t MaxOffset,
1685 LSRUse::KindType Kind, MemAccessTy AccessTy,
1687 bool HasBaseReg, int64_t Scale) {
1689 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1692 MinOffset = (uint64_t)BaseOffset + MinOffset;
1693 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1696 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1699 HasBaseReg, Scale) &&
1705 int64_t MinOffset, int64_t MaxOffset,
1706 LSRUse::KindType Kind, MemAccessTy AccessTy,
1707 const Formula &F,
const Loop &L) {
1715 assert((F.isCanonical(L) || F.Scale != 0));
1717 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1722 int64_t MaxOffset, LSRUse::KindType Kind,
1724 int64_t BaseOffset,
bool HasBaseReg, int64_t Scale) {
1727 BaseOffset, HasBaseReg, Scale) ||
1732 BaseGV, BaseOffset,
true, 0));
1736 int64_t MaxOffset, LSRUse::KindType Kind,
1737 MemAccessTy AccessTy,
const Formula &F) {
1738 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1739 F.BaseOffset, F.HasBaseReg, F.Scale);
1743 const LSRUse &LU,
const Formula &F) {
1746 for (
const LSRFixup &
Fixup : LU.Fixups)
1748 (F.BaseOffset + Fixup.Offset), F.HasBaseReg,
1749 F.Scale, Fixup.UserInst))
1755 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1760 const LSRUse &LU,
const Formula &F,
1769 return F.Scale != 1;
1775 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1776 F.Scale, LU.AccessTy.AddrSpace);
1778 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1779 F.Scale, LU.AccessTy.AddrSpace);
1781 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1782 "Legal addressing mode has an illegal cost!");
1783 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1785 case LSRUse::ICmpZero:
1787 case LSRUse::Special:
1797 LSRUse::KindType Kind, MemAccessTy AccessTy,
1801 if (BaseOffset == 0 && !BaseGV)
return true;
1805 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1809 if (!HasBaseReg && Scale == 1) {
1820 int64_t MaxOffset, LSRUse::KindType Kind,
1821 MemAccessTy AccessTy,
const SCEV *S,
1824 if (S->
isZero())
return true;
1832 if (!S->
isZero())
return false;
1835 if (BaseOffset == 0 && !BaseGV)
return true;
1839 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1842 BaseOffset, HasBaseReg, Scale);
1859 const SCEV *IncExpr;
1862 : UserInst(U), IVOperand(O), IncExpr(E) {}
1869 const SCEV *ExprBase =
nullptr;
1871 IVChain() =
default;
1872 IVChain(
const IVInc &Head,
const SCEV *
Base)
1873 : Incs(1, Head), ExprBase(Base) {}
1878 const_iterator
begin()
const {
1880 return std::next(Incs.
begin());
1882 const_iterator
end()
const {
1887 bool hasIncs()
const {
return Incs.
size() >= 2; }
1896 bool isProfitableIncrement(
const SCEV *OperExpr,
1897 const SCEV *IncExpr,
1919 bool FavorBackedgeIndex =
false;
1920 bool Changed =
false;
1943 RegUseTracker RegUses;
1948 static const unsigned MaxChains = 8;
1956 void OptimizeShadowIV();
1959 void OptimizeLoopTermCond();
1963 void FinalizeChain(IVChain &Chain);
1964 void CollectChains();
1968 void CollectInterestingTypesAndFactors();
1969 void CollectFixupsAndInitialFormulae();
1975 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
bool HasBaseReg,
1976 LSRUse::KindType Kind, MemAccessTy AccessTy);
1978 std::pair<size_t, int64_t> getUse(
const SCEV *&Expr, LSRUse::KindType Kind,
1979 MemAccessTy AccessTy);
1981 void DeleteUse(LSRUse &LU,
size_t LUIdx);
1983 LSRUse *FindUseWithSimilarFormula(
const Formula &F,
const LSRUse &OrigLU);
1985 void InsertInitialFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx);
1986 void InsertSupplementalFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx);
1987 void CountRegisters(
const Formula &F,
size_t LUIdx);
1988 bool InsertFormula(LSRUse &LU,
unsigned LUIdx,
const Formula &F);
1990 void CollectLoopInvariantFixupsAndFormulae();
1992 void GenerateReassociations(LSRUse &LU,
unsigned LUIdx, Formula
Base,
1993 unsigned Depth = 0);
1995 void GenerateReassociationsImpl(LSRUse &LU,
unsigned LUIdx,
1996 const Formula &Base,
unsigned Depth,
1997 size_t Idx,
bool IsScaledReg =
false);
1998 void GenerateCombinations(LSRUse &LU,
unsigned LUIdx, Formula Base);
1999 void GenerateSymbolicOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
2000 const Formula &Base,
size_t Idx,
2001 bool IsScaledReg =
false);
2002 void GenerateSymbolicOffsets(LSRUse &LU,
unsigned LUIdx, Formula Base);
2003 void GenerateConstantOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
2004 const Formula &Base,
2006 size_t Idx,
bool IsScaledReg =
false);
2007 void GenerateConstantOffsets(LSRUse &LU,
unsigned LUIdx, Formula Base);
2008 void GenerateICmpZeroScales(LSRUse &LU,
unsigned LUIdx, Formula Base);
2009 void GenerateScales(LSRUse &LU,
unsigned LUIdx, Formula Base);
2010 void GenerateTruncates(LSRUse &LU,
unsigned LUIdx, Formula Base);
2011 void GenerateCrossUseConstantOffsets();
2012 void GenerateAllReuseFormulae();
2014 void FilterOutUndesirableDedicatedRegisters();
2016 size_t EstimateSearchSpaceComplexity()
const;
2017 void NarrowSearchSpaceByDetectingSupersets();
2018 void NarrowSearchSpaceByCollapsingUnrolledCode();
2019 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
2020 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
2021 void NarrowSearchSpaceByDeletingCostlyFormulas();
2022 void NarrowSearchSpaceByPickingWinnerRegs();
2023 void NarrowSearchSpaceUsingHeuristics();
2028 const Cost &CurCost,
2042 Value *Expand(
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
2045 void RewriteForPHI(
PHINode *PN,
const LSRUse &LU,
const LSRFixup &LF,
2048 void Rewrite(
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
2058 bool getChanged()
const {
return Changed; }
2060 void print_factors_and_types(
raw_ostream &OS)
const;
2071 void LSRInstance::OptimizeShadowIV() {
2073 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2081 Type *DestTy =
nullptr;
2082 bool IsSigned =
false;
2096 if (
UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
2098 DestTy = UCast->getDestTy();
2100 else if (
SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
2102 DestTy = SCast->getDestTy();
2104 if (!DestTy)
continue;
2124 if (Mantissa == -1)
continue;
2128 unsigned Entry, Latch;
2138 if (!Init)
continue;
2145 if (!Incr)
continue;
2147 && Incr->getOpcode() != Instruction::Sub)
2152 if (Incr->getOperand(0) == PH)
2153 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2154 else if (Incr->getOperand(1) == PH)
2155 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2172 Instruction::FAdd : Instruction::FSub,
2173 NewPH, CFP,
"IV.S.next.", Incr);
2190 if (U.getUser() == Cond) {
2255 if (!Sel || !Sel->
hasOneUse())
return Cond;
2258 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2263 const SCEV *IterationCount = SE.
getAddExpr(One, BackedgeTakenCount);
2264 if (IterationCount != SE.
getSCEV(Sel))
return Cond;
2271 if (
const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2274 }
else if (
const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2277 }
else if (
const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2309 "Loop condition operand is an addrec in a different loop!");
2313 Value *NewRHS =
nullptr;
2317 if (
ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2318 if (BO1->isOne() && SE.
getSCEV(BO->getOperand(0)) == MaxRHS)
2319 NewRHS = BO->getOperand(0);
2321 if (
ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2322 if (BO1->isOne() && SE.
getSCEV(BO->getOperand(0)) == MaxRHS)
2323 NewRHS = BO->getOperand(0);
2330 else if (
const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2331 NewRHS = SU->getValue();
2359 LSRInstance::OptimizeLoopTermCond() {
2378 return LatchBlock != BB;
2386 for (
BasicBlock *ExitingBlock : ExitingBlocks) {
2402 if (!FindIVUserForCond(Cond, CondUse))
2411 Cond = OptimizeMax(Cond, CondUse);
2416 if (!DT.dominates(ExitingBlock, LatchBlock))
2421 if (LatchBlock != ExitingBlock)
2425 if (&*UI != CondUse &&
2426 !DT.properlyDominates(UI->getUser()->getParent(), ExitingBlock)) {
2429 const SCEV *A = IU.getStride(*CondUse, L);
2430 const SCEV *
B = IU.getStride(*UI, L);
2431 if (!A || !B)
continue;
2441 dyn_cast_or_null<SCEVConstant>(
getExactSDiv(B, A, SE))) {
2445 goto decline_post_inc;
2449 goto decline_post_inc;
2451 if (
isAddressUse(TTI, UI->getUser(), UI->getOperandValToReplace())) {
2453 TTI, UI->getUser(), UI->getOperandValToReplace());
2458 AccessTy.AddrSpace))
2459 goto decline_post_inc;
2464 AccessTy.AddrSpace))
2465 goto decline_post_inc;
2470 LLVM_DEBUG(
dbgs() <<
" Change loop exiting icmp to use postinc iv: " 2482 Cond = cast<ICmpInst>(Cond->
clone());
2484 ExitingBlock->getInstList().insert(TermBr->
getIterator(), Cond);
2508 DT.findNearestCommonDominator(IVIncInsertPos->getParent(),
2511 IVIncInsertPos = Inst;
2512 else if (BB != IVIncInsertPos->
getParent())
2519 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2520 bool HasBaseReg, LSRUse::KindType Kind,
2521 MemAccessTy AccessTy) {
2522 int64_t NewMinOffset = LU.MinOffset;
2523 int64_t NewMaxOffset = LU.MaxOffset;
2524 MemAccessTy NewAccessTy = AccessTy;
2529 if (LU.Kind != Kind)
2536 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2537 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2538 AccessTy.AddrSpace);
2543 if (NewOffset < LU.MinOffset) {
2545 LU.MaxOffset - NewOffset, HasBaseReg))
2547 NewMinOffset = NewOffset;
2548 }
else if (NewOffset > LU.MaxOffset) {
2550 NewOffset - LU.MinOffset, HasBaseReg))
2552 NewMaxOffset = NewOffset;
2556 LU.MinOffset = NewMinOffset;
2557 LU.MaxOffset = NewMaxOffset;
2558 LU.AccessTy = NewAccessTy;
2565 std::pair<size_t, int64_t> LSRInstance::getUse(
const SCEV *&Expr,
2566 LSRUse::KindType Kind,
2567 MemAccessTy AccessTy) {
2568 const SCEV *Copy = Expr;
2578 std::pair<UseMapTy::iterator, bool>
P =
2582 size_t LUIdx = P.first->second;
2583 LSRUse &LU = Uses[LUIdx];
2584 if (reconcileNewOffset(LU, Offset,
true, Kind, AccessTy))
2586 return std::make_pair(LUIdx, Offset);
2590 size_t LUIdx = Uses.size();
2591 P.first->second = LUIdx;
2592 Uses.push_back(LSRUse(Kind, AccessTy));
2593 LSRUse &LU = Uses[LUIdx];
2597 return std::make_pair(LUIdx, Offset);
2601 void LSRInstance::DeleteUse(LSRUse &LU,
size_t LUIdx) {
2602 if (&LU != &Uses.back())
2607 RegUses.swapAndDropUse(LUIdx, Uses.size());
2613 LSRInstance::FindUseWithSimilarFormula(
const Formula &OrigF,
2614 const LSRUse &OrigLU) {
2616 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2617 LSRUse &LU = Uses[LUIdx];
2623 if (&LU != &OrigLU &&
2624 LU.Kind != LSRUse::ICmpZero &&
2625 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2626 LU.WidestFixupType == OrigLU.WidestFixupType &&
2627 LU.HasFormulaWithSameRegs(OrigF)) {
2629 for (
const Formula &F : LU.Formulae) {
2632 if (F.BaseRegs == OrigF.BaseRegs &&
2633 F.ScaledReg == OrigF.ScaledReg &&
2634 F.BaseGV == OrigF.BaseGV &&
2635 F.Scale == OrigF.Scale &&
2636 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2637 if (F.BaseOffset == 0)
2652 void LSRInstance::CollectInterestingTypesAndFactors() {
2658 const SCEV *Expr = IU.getExpr(U);
2668 if (AR->getLoop() == L)
2669 Strides.
insert(AR->getStepRecurrence(SE));
2674 }
while (!Worklist.
empty());
2679 I = Strides.
begin(),
E = Strides.
end(); I !=
E; ++
I)
2681 std::next(I); NewStrideIter !=
E; ++NewStrideIter) {
2682 const SCEV *OldStride = *
I;
2683 const SCEV *NewStride = *NewStrideIter;
2694 dyn_cast_or_null<SCEVConstant>(
getExactSDiv(NewStride, OldStride,
2696 if (Factor->getAPInt().getMinSignedBits() <= 64)
2697 Factors.insert(Factor->getAPInt().getSExtValue());
2702 if (Factor->getAPInt().getMinSignedBits() <= 64)
2703 Factors.insert(Factor->getAPInt().getSExtValue());
2709 if (Types.size() == 1)
2721 for(; OI != OE; ++OI) {
2722 if (
Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2727 dyn_cast<SCEVAddRecExpr>(SE.
getSCEV(Oper))) {
2728 if (AR->getLoop() == L)
2739 if (
TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2740 return Trunc->getOperand(0);
2773 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2775 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2777 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2783 for (std::reverse_iterator<SCEVAddExpr::op_iterator>
I(Add->
op_end()),
2785 const SCEV *SubExpr = *
I;
2795 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2804 bool IVChain::isProfitableIncrement(
const SCEV *OperExpr,
2805 const SCEV *IncExpr,
2813 if (!isa<SCEVConstant>(IncExpr)) {
2815 if (isa<SCEVConstant>(SE.
getMinusSCEV(OperExpr, HeadExpr)))
2839 if (!Chain.hasIncs())
2842 if (!Users.
empty()) {
2843 LLVM_DEBUG(
dbgs() <<
"Chain: " << *Chain.Incs[0].UserInst <<
" users:\n";
2845 : Users) {
dbgs() <<
" " << *Inst <<
"\n"; });
2848 assert(!Chain.Incs.empty() &&
"empty IV chains are not allowed");
2856 if (isa<PHINode>(Chain.tailUserInst())
2857 && SE.
getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2860 const SCEV *LastIncExpr =
nullptr;
2861 unsigned NumConstIncrements = 0;
2862 unsigned NumVarIncrements = 0;
2863 unsigned NumReusedIncrements = 0;
2864 for (
const IVInc &Inc : Chain) {
2865 if (Inc.IncExpr->isZero())
2870 if (isa<SCEVConstant>(Inc.IncExpr)) {
2871 ++NumConstIncrements;
2875 if (Inc.IncExpr == LastIncExpr)
2876 ++NumReusedIncrements;
2880 LastIncExpr = Inc.IncExpr;
2885 if (NumConstIncrements > 1)
2892 cost += NumVarIncrements;
2896 cost -= NumReusedIncrements;
2898 LLVM_DEBUG(
dbgs() <<
"Chain: " << *Chain.Incs[0].UserInst <<
" Cost: " << cost
2915 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2916 const SCEV *LastIncExpr =
nullptr;
2917 for (; ChainIdx < NChains; ++ChainIdx) {
2918 IVChain &Chain = IVChainVec[ChainIdx];
2924 if (!StressIVChain && Chain.ExprBase != OperExprBase)
2932 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2941 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2942 LastIncExpr = IncExpr;
2948 if (ChainIdx == NChains) {
2949 if (isa<PHINode>(UserInst))
2951 if (NChains >= MaxChains && !StressIVChain) {
2955 LastIncExpr = OperExpr;
2959 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2962 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2964 ChainUsersVec.
resize(NChains);
2965 LLVM_DEBUG(
dbgs() <<
"IV Chain#" << ChainIdx <<
" Head: (" << *UserInst
2966 <<
") IV=" << *LastIncExpr <<
"\n");
2968 LLVM_DEBUG(
dbgs() <<
"IV Chain#" << ChainIdx <<
" Inc: (" << *UserInst
2969 <<
") IV+" << *LastIncExpr <<
"\n");
2971 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2973 IVChain &Chain = IVChainVec[ChainIdx];
2977 if (!LastIncExpr->
isZero()) {
2978 ChainUsersVec[ChainIdx].FarUsers.
insert(NearUsers.
begin(),
2994 IVChain::const_iterator IncIter = Chain.Incs.begin();
2995 IVChain::const_iterator IncEnd = Chain.Incs.end();
2996 for( ; IncIter != IncEnd; ++IncIter) {
2997 if (IncIter->UserInst == OtherUse)
3000 if (IncIter != IncEnd)
3004 && !isa<SCEVUnknown>(SE.
getSCEV(OtherUse))
3005 && IU.isIVUserOrOperand(OtherUse)) {
3008 NearUsers.
insert(OtherUse);
3013 ChainUsersVec[ChainIdx].FarUsers.
erase(UserInst);
3038 void LSRInstance::CollectChains() {
3045 Rung->
getBlock() != LoopHeader; Rung = Rung->getIDom()) {
3054 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
3064 for (
unsigned ChainIdx = 0, NChains = IVChainVec.size();
3065 ChainIdx < NChains; ++ChainIdx) {
3066 ChainUsersVec[ChainIdx].NearUsers.
erase(&I);
3072 while (IVOpIter != IVOpEnd) {
3073 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
3074 if (UniqueOperands.
insert(IVOpInst).second)
3075 ChainInstruction(&I, IVOpInst, ChainUsersVec);
3076 IVOpIter =
findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3088 ChainInstruction(&PN, IncV, ChainUsersVec);
3091 unsigned ChainIdx = 0;
3092 for (
unsigned UsersIdx = 0, NChains = IVChainVec.size();
3093 UsersIdx < NChains; ++UsersIdx) {
3095 ChainUsersVec[UsersIdx].FarUsers, SE))
3098 if (ChainIdx != UsersIdx)
3099 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
3100 FinalizeChain(IVChainVec[ChainIdx]);
3103 IVChainVec.resize(ChainIdx);
3106 void LSRInstance::FinalizeChain(IVChain &Chain) {
3107 assert(!Chain.Incs.empty() &&
"empty IV chains are not allowed");
3108 LLVM_DEBUG(
dbgs() <<
"Final Chain: " << *Chain.Incs[0].UserInst <<
"\n");
3110 for (
const IVInc &Inc : Chain) {
3112 auto UseI =
find(Inc.UserInst->operands(), Inc.IVOperand);
3113 assert(UseI != Inc.UserInst->op_end() &&
"cannot find IV operand");
3114 IVIncSet.insert(UseI);
3122 if (!IncConst || !
isAddressUse(TTI, UserInst, Operand))
3128 MemAccessTy AccessTy =
getAccessType(TTI, UserInst, Operand);
3143 const IVInc &Head = Chain.Incs[0];
3148 Value *IVSrc =
nullptr;
3149 while (IVOpIter != IVOpEnd) {
3160 if (SE.
getSCEV(*IVOpIter) == Head.IncExpr
3161 || SE.
getSCEV(IVSrc) == Head.IncExpr) {
3164 IVOpIter =
findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3166 if (IVOpIter == IVOpEnd) {
3168 LLVM_DEBUG(
dbgs() <<
"Concealed chain head: " << *Head.UserInst <<
"\n");
3171 assert(IVSrc &&
"Failed to find IV chain source");
3174 Type *IVTy = IVSrc->getType();
3176 const SCEV *LeftOverExpr =
nullptr;
3177 for (
const IVInc &Inc : Chain) {
3179 if (isa<PHINode>(InsertPt))
3180 InsertPt = L->getLoopLatch()->getTerminator();
3184 Value *IVOper = IVSrc;
3185 if (!Inc.IncExpr->isZero()) {
3189 LeftOverExpr = LeftOverExpr ?
3190 SE.
getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3192 if (LeftOverExpr && !LeftOverExpr->
isZero()) {
3198 IVOper = Rewriter.
expandCodeFor(IVOperExpr, IVTy, InsertPt);
3202 assert(IVTy == IVOper->
getType() &&
"inconsistent IV increment type");
3204 LeftOverExpr =
nullptr;
3207 Type *OperTy = Inc.IVOperand->getType();
3208 if (IVTy != OperTy) {
3210 "cannot extend a chained IV");
3212 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy,
"lsr.chain");
3214 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3219 if (isa<PHINode>(Chain.tailUserInst())) {
3220 for (
PHINode &Phi : L->getHeader()->phis()) {
3224 Phi.getIncomingValueForBlock(L->getLoopLatch()));
3227 Value *IVOper = IVSrc;
3229 if (IVTy != PostIncTy) {
3231 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3233 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy,
"lsr.chain");
3235 Phi.replaceUsesOfWith(PostIncV, IVOper);
3241 void LSRInstance::CollectFixupsAndInitialFormulae() {
3243 bool SaveCmp = TTI.
canSaveCmp(L, &ExitBranch, &SE, &LI, &DT, &AC, &LibInfo);
3249 find(UserInst->
operands(), U.getOperandValToReplace());
3250 assert(UseI != UserInst->
op_end() &&
"cannot find IV operand");
3251 if (IVIncSet.count(UseI)) {
3252 LLVM_DEBUG(
dbgs() <<
"Use is in profitable chain: " << **UseI <<
'\n');
3257 MemAccessTy AccessTy;
3258 if (
isAddressUse(TTI, UserInst, U.getOperandValToReplace())) {
3260 AccessTy =
getAccessType(TTI, UserInst, U.getOperandValToReplace());
3263 const SCEV *S = IU.getExpr(U);
3272 if (
ICmpInst *CI = dyn_cast<ICmpInst>(UserInst)) {
3275 if (SaveCmp && CI == dyn_cast<ICmpInst>(ExitBranch->
getCondition()))
3277 if (CI->isEquality()) {
3280 Value *
NV = CI->getOperand(1);
3281 if (NV == U.getOperandValToReplace()) {
3282 CI->setOperand(1, CI->getOperand(0));
3283 CI->setOperand(0, NV);
3284 NV = CI->getOperand(1);
3294 Kind = LSRUse::ICmpZero;
3300 for (
size_t i = 0,
e = Factors.size(); i !=
e; ++i)
3301 if (Factors[i] != -1)
3302 Factors.insert(-(uint64_t)Factors[i]);
3308 std::pair<size_t, int64_t>
P = getUse(S, Kind, AccessTy);
3309 size_t LUIdx = P.first;
3310 int64_t
Offset = P.second;
3311 LSRUse &LU = Uses[LUIdx];
3314 LSRFixup &LF = LU.getNewFixup();
3315 LF.UserInst = UserInst;
3316 LF.OperandValToReplace = U.getOperandValToReplace();
3317 LF.PostIncLoops = TmpPostIncLoops;
3319 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3321 if (!LU.WidestFixupType ||
3324 LU.WidestFixupType = LF.OperandValToReplace->getType();
3327 if (LU.Formulae.empty()) {
3328 InsertInitialFormula(S, LU, LUIdx);
3329 CountRegisters(LU.Formulae.back(), LUIdx);
3339 LSRInstance::InsertInitialFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx) {
3342 LU.RigidFormula =
true;
3345 F.initialMatch(S, L, SE);
3346 bool Inserted = InsertFormula(LU, LUIdx, F);
3347 assert(Inserted &&
"Initial formula already exists!"); (void)Inserted;
3353 LSRInstance::InsertSupplementalFormula(
const SCEV *S,
3354 LSRUse &LU,
size_t LUIdx) {
3356 F.BaseRegs.push_back(S);
3357 F.HasBaseReg =
true;
3358 bool Inserted = InsertFormula(LU, LUIdx, F);
3359 assert(Inserted &&
"Supplemental formula already exists!"); (void)Inserted;
3363 void LSRInstance::CountRegisters(
const Formula &F,
size_t LUIdx) {
3365 RegUses.countRegister(F.ScaledReg, LUIdx);
3366 for (
const SCEV *BaseReg : F.BaseRegs)
3367 RegUses.countRegister(BaseReg, LUIdx);
3372 bool LSRInstance::InsertFormula(LSRUse &LU,
unsigned LUIdx,
const Formula &F) {
3374 assert(
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3375 "Formula is illegal");
3377 if (!LU.InsertFormula(F, *L))
3380 CountRegisters(F, LUIdx);
3390 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3394 while (!Worklist.empty()) {
3395 const SCEV *S = Worklist.pop_back_val();
3398 if (!Visited.
insert(S).second)
3402 Worklist.append(
N->op_begin(),
N->op_end());
3405 else if (
const SCEVUDivExpr *
D = dyn_cast<SCEVUDivExpr>(S)) {
3406 Worklist.push_back(
D->getLHS());
3407 Worklist.push_back(
D->getRHS());
3408 }
else if (
const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3409 const Value *V = US->getValue();
3410 if (
const Instruction *Inst = dyn_cast<Instruction>(V)) {
3413 }
else if (isa<UndefValue>(V))
3416 for (
const Use &U : V->
uses()) {
3426 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3428 cast<PHINode>(UserInst)->getIncomingBlock(
3430 if (!DT.dominates(L->
getHeader(), UseBB))
3441 const SCEV *UserS = SE.
getSCEV(const_cast<Instruction *>(UserInst));
3443 if (!isa<SCEVUnknown>(UserS))
3447 SE.
getUnknown(const_cast<Instruction *>(UserInst)));
3452 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3453 unsigned OtherIdx = !U.getOperandNo();
3454 Value *OtherOp =
const_cast<Value *
>(ICI->getOperand(OtherIdx));
3459 std::pair<size_t, int64_t>
P = getUse(
3461 size_t LUIdx = P.first;
3462 int64_t
Offset = P.second;
3463 LSRUse &LU = Uses[LUIdx];
3464 LSRFixup &LF = LU.getNewFixup();
3465 LF.UserInst =
const_cast<Instruction *
>(UserInst);
3466 LF.OperandValToReplace = U;
3468 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3469 if (!LU.WidestFixupType ||
3472 LU.WidestFixupType = LF.OperandValToReplace->getType();
3473 InsertSupplementalFormula(US, LU, LUIdx);
3474 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3490 unsigned Depth = 0) {
3497 for (
const SCEV *S :
Add->operands()) {
3503 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3505 if (AR->getStart()->isZero() || !AR->isAffine())
3512 if (Remainder && (AR->getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3513 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3514 Remainder =
nullptr;
3516 if (Remainder != AR->getStart()) {
3518 Remainder = SE.getConstant(AR->getType(), 0);
3519 return SE.getAddRecExpr(Remainder,
3520 AR->getStepRecurrence(SE),
3525 }
else if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3527 if (Mul->getNumOperands() != 2)
3530 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3531 C = C ? cast<SCEVConstant>(SE.
getMulExpr(C, Op0)) : Op0;
3532 const SCEV *Remainder =
3535 Ops.push_back(SE.getMulExpr(C, Remainder));
3545 LSRUse &LU,
const SCEV *S,
const Loop *L,
3548 !LU.AccessTy.getType()->isIntOrIntVectorTy())
3554 if (!isa<SCEVConstant>(LoopStep))
3556 if (LU.AccessTy.getType()->getScalarSizeInBits() !=
3563 if (!isa<SCEVConstant>(LoopStart) && SE.
isLoopInvariant(LoopStart, L))
3570 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU,
unsigned LUIdx,
3571 const Formula &
Base,
3572 unsigned Depth,
size_t Idx,
3574 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3586 if (AddOps.
size() == 1)
3600 LU.AccessTy, *J, Base.getNumRegs() > 1))
3606 InnerAddOps.
append(std::next(J),
3611 if (InnerAddOps.
size() == 1 &&
3613 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3629 F.ScaledReg =
nullptr;
3631 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3632 }
else if (IsScaledReg)
3633 F.ScaledReg = InnerSum;
3635 F.BaseRegs[Idx] = InnerSum;
3645 F.BaseRegs.push_back(*J);
3650 if (InsertFormula(LU, LUIdx, F))
3657 GenerateReassociations(LU, LUIdx, LU.Formulae.back(),
3663 void LSRInstance::GenerateReassociations(LSRUse &LU,
unsigned LUIdx,
3664 Formula Base,
unsigned Depth) {
3665 assert(Base.isCanonical(*L) &&
"Input must be in the canonical form");
3670 for (
size_t i = 0,
e = Base.BaseRegs.size(); i !=
e; ++i)
3671 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3673 if (Base.Scale == 1)
3674 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3680 void LSRInstance::GenerateCombinations(LSRUse &LU,
unsigned LUIdx,
3683 if (Base.BaseRegs.size() + (Base.Scale == 1) +
3684 (Base.UnfoldedOffset != 0) <= 1)
3691 Formula NewBase = Base;
3692 NewBase.BaseRegs.clear();
3693 Type *CombinedIntegerType =
nullptr;
3694 for (
const SCEV *BaseReg : Base.BaseRegs) {
3697 if (!CombinedIntegerType)
3702 NewBase.BaseRegs.push_back(BaseReg);
3706 if (Ops.
size() == 0)
3711 auto GenerateFormula = [&](
const SCEV *Sum) {
3712 Formula F = NewBase;
3720 F.BaseRegs.push_back(Sum);
3722 (void)InsertFormula(LU, LUIdx, F);
3726 if (Ops.
size() > 1) {
3733 if (NewBase.UnfoldedOffset) {
3734 assert(CombinedIntegerType &&
"Missing a type for the unfolded offset");
3737 NewBase.UnfoldedOffset = 0;
3743 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
3744 const Formula &Base,
size_t Idx,
3746 const SCEV *
G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3752 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3757 F.BaseRegs[Idx] =
G;
3758 (void)InsertFormula(LU, LUIdx, F);
3762 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU,
unsigned LUIdx,
3765 if (Base.BaseGV)
return;
3767 for (
size_t i = 0,
e = Base.BaseRegs.size(); i !=
e; ++i)
3768 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3769 if (Base.Scale == 1)
3770 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, -1,
3775 void LSRInstance::GenerateConstantOffsetsImpl(
3776 LSRUse &LU,
unsigned LUIdx,
const Formula &Base,
3779 auto GenerateOffset = [&](
const SCEV *
G, int64_t
Offset) {
3781 F.BaseOffset = (uint64_t)Base.BaseOffset -
Offset;
3791 F.ScaledReg =
nullptr;
3793 F.deleteBaseReg(F.BaseRegs[Idx]);
3795 }
else if (IsScaledReg)
3798 F.BaseRegs[Idx] = NewG;
3800 (void)InsertFormula(LU, LUIdx, F);
3804 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3815 if (
auto *GAR = dyn_cast<SCEVAddRecExpr>(G)) {
3817 dyn_cast<SCEVConstant>(GAR->getStepRecurrence(SE))) {
3818 const APInt &StepInt = StepRec->getAPInt();
3822 for (int64_t
Offset : Worklist) {
3824 GenerateOffset(G,
Offset);
3829 for (int64_t
Offset : Worklist)
3830 GenerateOffset(G,
Offset);
3833 if (G->
isZero() || Imm == 0)
3836 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3837 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3842 F.BaseRegs[Idx] =
G;
3843 (void)InsertFormula(LU, LUIdx, F);
3847 void LSRInstance::GenerateConstantOffsets(LSRUse &LU,
unsigned LUIdx,
3853 if (LU.MaxOffset != LU.MinOffset)
3856 for (
size_t i = 0,
e = Base.BaseRegs.size(); i !=
e; ++i)
3857 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3858 if (Base.Scale == 1)
3859 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, -1,
3865 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU,
unsigned LUIdx,
3867 if (LU.Kind != LSRUse::ICmpZero)
return;
3870 Type *IntTy = Base.getType();
3875 if (LU.MinOffset != LU.MaxOffset)
return;
3878 if (Base.ScaledReg && Base.ScaledReg->getType()->isPointerTy())
3880 for (
const SCEV *BaseReg : Base.BaseRegs)
3883 assert(!Base.BaseGV &&
"ICmpZero use is not legal!");
3886 for (int64_t Factor : Factors) {
3888 if (Base.BaseOffset == std::numeric_limits<int64_t>::min() && Factor == -1)
3890 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3891 if (NewBaseOffset / Factor != Base.BaseOffset)
3899 int64_t
Offset = LU.MinOffset;
3900 if (Offset == std::numeric_limits<int64_t>::min() && Factor == -1)
3902 Offset = (uint64_t)Offset * Factor;
3903 if (Offset / Factor != LU.MinOffset)
3911 F.BaseOffset = NewBaseOffset;
3914 if (!
isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3918 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3923 for (
size_t i = 0,
e = F.BaseRegs.size(); i !=
e; ++i) {
3924 F.BaseRegs[i] = SE.
getMulExpr(F.BaseRegs[i], FactorS);
3925 if (
getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3931 F.ScaledReg = SE.
getMulExpr(F.ScaledReg, FactorS);
3932 if (
getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3937 if (F.UnfoldedOffset != 0) {
3938 if (F.UnfoldedOffset == std::numeric_limits<int64_t>::min() &&
3941 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3942 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3951 (void)InsertFormula(LU, LUIdx, F);
3958 void LSRInstance::GenerateScales(LSRUse &LU,
unsigned LUIdx, Formula Base) {
3960 Type *IntTy = Base.getType();
3965 if (Base.Scale != 0 && !Base.unscale())
3968 assert(Base.Scale == 0 &&
"unscale did not did its job!");
3971 for (int64_t Factor : Factors) {
3972 Base.Scale = Factor;
3973 Base.HasBaseReg = Base.BaseRegs.size() > 1;
3975 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3980 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3981 LU.AccessTy, Base) &&
3982 LU.AllFixupsOutsideLoop)
3983 LU.Kind = LSRUse::Special;
3989 if (LU.Kind == LSRUse::ICmpZero &&
3990 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3993 for (
size_t i = 0,
e = Base.BaseRegs.size(); i !=
e; ++i) {
3995 if (AR && (AR->
getLoop() == L || LU.AllFixupsOutsideLoop)) {
4004 F.ScaledReg = Quotient;
4005 F.deleteBaseReg(F.BaseRegs[i]);
4009 if (F.Scale == 1 && (F.BaseRegs.empty() ||
4010 (AR->
getLoop() != L && LU.AllFixupsOutsideLoop)))
4014 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
4016 (void)InsertFormula(LU, LUIdx, F);
4024 void LSRInstance::GenerateTruncates(LSRUse &LU,
unsigned LUIdx, Formula Base) {
4026 if (Base.BaseGV)
return;
4029 Type *DstTy = Base.getType();
4033 for (
Type *SrcTy : Types) {
4043 if (NewScaledReg->
isZero())
4045 F.ScaledReg = NewScaledReg;
4047 bool HasZeroBaseReg =
false;
4048 for (
const SCEV *&BaseReg : F.BaseRegs) {
4050 if (NewBaseReg->
isZero()) {
4051 HasZeroBaseReg =
true;
4054 BaseReg = NewBaseReg;
4061 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
4065 (void)InsertFormula(LU, LUIdx, F);
4078 const SCEV *OrigReg;
4080 WorkItem(
size_t LI, int64_t I,
const SCEV *R)
4081 : LUIdx(LI), Imm(I), OrigReg(R) {}
4089 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 4091 OS <<
"in formulae referencing " << *OrigReg <<
" in use " << LUIdx
4092 <<
" , add offset " << Imm;
4102 void LSRInstance::GenerateCrossUseConstantOffsets() {
4104 using ImmMapTy = std::map<int64_t, const SCEV *>;
4109 for (
const SCEV *
Use : RegUses) {
4112 auto Pair = Map.
insert(std::make_pair(Reg, ImmMapTy()));
4115 Pair.first->second.insert(std::make_pair(Imm,
Use));
4116 UsedByIndicesMap[
Reg] |= RegUses.getUsedByIndices(
Use);
4124 for (
const SCEV *Reg : Sequence) {
4125 const ImmMapTy &Imms = Map.
find(Reg)->second;
4128 if (Imms.size() == 1)
4131 LLVM_DEBUG(
dbgs() <<
"Generating cross-use offsets for " << *Reg <<
':';
4132 for (
const auto &
Entry 4134 <<
' ' <<
Entry.first;
4138 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
4140 const SCEV *OrigReg = J->second;
4142 int64_t JImm = J->first;
4143 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
4145 if (!isa<SCEVConstant>(OrigReg) &&
4146 UsedByIndicesMap[Reg].
count() == 1) {
4154 int64_t First = Imms.begin()->first;
4155 int64_t Last = std::prev(Imms.end())->
first;
4158 int64_t Avg = (First & Last) + ((First ^ Last) >> 1);
4161 Avg = Avg + ((First ^ Last) & ((uint64_t)Avg >> 63));
4162 ImmMapTy::const_iterator OtherImms[] = {
4163 Imms.begin(), std::prev(Imms.end()),
4164 Imms.lower_bound(Avg)};
4166 ImmMapTy::const_iterator M = OtherImms[i];
4167 if (M == J || M == JE)
continue;
4170 int64_t Imm = (uint64_t)JImm - M->first;
4173 if (UniqueItems.
insert(std::make_pair(LUIdx, Imm)).second)
4174 WorkItems.
push_back(WorkItem(LUIdx, Imm, OrigReg));
4181 UsedByIndicesMap.
clear();
4182 UniqueItems.
clear();
4185 for (
const WorkItem &WI : WorkItems) {
4186 size_t LUIdx = WI.LUIdx;
4187 LSRUse &LU = Uses[LUIdx];
4188 int64_t Imm = WI.Imm;
4189 const SCEV *OrigReg = WI.OrigReg;
4196 for (
size_t L = 0,
LE = LU.Formulae.size(); L !=
LE; ++L) {
4197 Formula F = LU.Formulae[L];
4204 if (F.ScaledReg == OrigReg) {
4205 int64_t
Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
4207 if (F.referencesReg(SE.
getSCEV(
4211 NewF.BaseOffset =
Offset;
4212 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
4215 NewF.ScaledReg = SE.
getAddExpr(NegImmS, NewF.ScaledReg);
4220 if (
const SCEVConstant *
C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
4221 if (
C->getValue()->isNegative() != (NewF.BaseOffset < 0) &&
4222 (
C->getAPInt().abs() *
APInt(BitWidth, F.Scale))
4227 NewF.canonicalize(*this->L);
4228 (void)InsertFormula(LU, LUIdx, NewF);
4231 for (
size_t N = 0,
NE = F.BaseRegs.size();
N !=
NE; ++
N) {
4232 const SCEV *BaseReg = F.BaseRegs[
N];
4233 if (BaseReg != OrigReg)
4236 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
4238 LU.Kind, LU.AccessTy, NewF)) {
4245 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
4247 NewF.BaseRegs[
N] = SE.
getAddExpr(NegImmS, BaseReg);
4252 for (
const SCEV *NewReg : NewF.BaseRegs)
4254 if ((
C->getAPInt() + NewF.BaseOffset)
4258 countTrailingZeros<uint64_t>(NewF.BaseOffset))
4262 NewF.canonicalize(*this->L);
4263 (void)InsertFormula(LU, LUIdx, NewF);
4274 LSRInstance::GenerateAllReuseFormulae() {
4277 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4278 LSRUse &LU = Uses[LUIdx];
4279 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4280 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4281 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4282 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4284 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4285 LSRUse &LU = Uses[LUIdx];
4286 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4287 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4288 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4289 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4290 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4291 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4292 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4293 GenerateScales(LU, LUIdx, LU.Formulae[i]);
4295 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4296 LSRUse &LU = Uses[LUIdx];
4297 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4298 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4301 GenerateCrossUseConstantOffsets();
4304 "After generating reuse formulae:\n";
4305 print_uses(
dbgs()));
4310 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4315 bool ChangedFormulae =
false;
4320 using BestFormulaeTy =
4323 BestFormulaeTy BestFormulae;
4325 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4326 LSRUse &LU = Uses[LUIdx];
4331 for (
size_t FIdx = 0, NumForms = LU.Formulae.size();
4332 FIdx != NumForms; ++FIdx) {
4333 Formula &F = LU.Formulae[FIdx];
4342 Cost CostF(L, SE, TTI);
4344 CostF.RateFormula(F, Regs, VisitedRegs, LU, &LoserRegs);
4345 if (CostF.isLoser()) {
4357 for (
const SCEV *Reg : F.BaseRegs) {
4358 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4362 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4368 std::pair<BestFormulaeTy::const_iterator, bool>
P =
4369 BestFormulae.insert(std::make_pair(Key, FIdx));
4373 Formula &Best = LU.Formulae[P.first->second];
4375 Cost CostBest(L, SE, TTI);
4377 CostBest.RateFormula(Best, Regs, VisitedRegs, LU);
4378 if (CostF.isLess(CostBest))
4382 " in favor of formula ";
4383 Best.print(
dbgs());
dbgs() <<
'\n');
4386 ChangedFormulae =
true;
4388 LU.DeleteFormula(F);
4396 LU.RecomputeRegs(LUIdx, RegUses);
4399 BestFormulae.clear();
4404 "After filtering out undesirable candidates:\n";
4412 size_t LSRInstance::EstimateSearchSpaceComplexity()
const {
4414 for (
const LSRUse &LU : Uses) {
4415 size_t FSize = LU.Formulae.size();
4430 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4434 LLVM_DEBUG(
dbgs() <<
"Narrowing the search space by eliminating formulae " 4435 "which use a superset of registers used by other " 4438 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4439 LSRUse &LU = Uses[LUIdx];
4441 for (
size_t i = 0,
e = LU.Formulae.size(); i !=
e; ++i) {
4442 Formula &F = LU.Formulae[i];
4447 I = F.BaseRegs.begin(),
E = F.BaseRegs.end(); I !=
E; ++
I) {
4452 NewF.BaseOffset += (uint64_t)
C->getValue()->getSExtValue();
4453 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4454 (I - F.BaseRegs.begin()));
4455 if (LU.HasFormulaWithSameRegs(NewF)) {
4458 LU.DeleteFormula(F);
4464 }
else if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4465 if (
GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4469 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4470 (I - F.BaseRegs.begin()));
4471 if (LU.HasFormulaWithSameRegs(NewF)) {
4474 LU.DeleteFormula(F);
4485 LU.RecomputeRegs(LUIdx, RegUses);
4494 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4499 dbgs() <<
"The search space is too complex.\n" 4500 "Narrowing the search space by assuming that uses separated " 4501 "by a constant offset will use the same registers.\n");
4505 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4506 LSRUse &LU = Uses[LUIdx];
4507 for (
const Formula &F : LU.Formulae) {
4508 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4511 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4515 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset,
false,
4516 LU.Kind, LU.AccessTy))
4521 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4524 for (LSRFixup &
Fixup : LU.Fixups) {
4525 Fixup.Offset += F.BaseOffset;
4526 LUThatHas->pushFixup(Fixup);
4527 LLVM_DEBUG(
dbgs() <<
"New fixup has offset " << Fixup.Offset <<
'\n');
4532 for (
size_t i = 0,
e = LUThatHas->Formulae.size(); i !=
e; ++i) {
4533 Formula &F = LUThatHas->Formulae[i];
4534 if (!
isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4535 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4537 LUThatHas->DeleteFormula(F);
4545 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4548 DeleteUse(LU, LUIdx);
4561 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4565 LLVM_DEBUG(
dbgs() <<
"Narrowing the search space by re-filtering out " 4566 "undesirable dedicated registers.\n");
4568 FilterOutUndesirableDedicatedRegisters();
4583 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4588 dbgs() <<
"The search space is too complex.\n" 4589 "Narrowing the search space by choosing the best Formula " 4590 "from the Formulae with the same Scale and ScaledReg.\n");
4595 BestFormulaeTy BestFormulae;
4597 bool ChangedFormulae =
false;
4602 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4603 LSRUse &LU = Uses[LUIdx];
4608 auto IsBetterThan = [&](Formula &FA, Formula &FB) {
4613 size_t FARegNum = 0;
4614 for (
const SCEV *Reg : FA.BaseRegs) {
4615 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4616 FARegNum += (NumUses - UsedByIndices.
count() + 1);
4618 size_t FBRegNum = 0;
4619 for (
const SCEV *Reg : FB.BaseRegs) {
4620 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4621 FBRegNum += (NumUses - UsedByIndices.
count() + 1);
4623 if (FARegNum != FBRegNum)
4624 return FARegNum < FBRegNum;
4628 Cost CostFA(L, SE, TTI);
4629 Cost CostFB(L, SE, TTI);
4631 CostFA.RateFormula(FA, Regs, VisitedRegs, LU);
4633 CostFB.RateFormula(FB, Regs, VisitedRegs, LU);
4634 return CostFA.isLess(CostFB);
4638 for (
size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4640 Formula &F = LU.Formulae[FIdx];
4643 auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
4647 Formula &Best = LU.Formulae[
P.first->second];
4648 if (IsBetterThan(F, Best))
4652 " in favor of formula ";
4653 Best.print(
dbgs());
dbgs() <<
'\n');
4655 ChangedFormulae =
true;
4657 LU.DeleteFormula(F);
4663 LU.RecomputeRegs(LUIdx, RegUses);
4666 BestFormulae.clear();
4671 "After filtering out undesirable candidates:\n";
4718 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4732 for (
const SCEV *Reg : RegUses) {
4733 if (UniqRegs.
count(Reg))
4736 for (
const LSRUse &LU : Uses) {
4737 if (!LU.Regs.count(Reg))
4739 float P = LU.getNotSelectedProbability(Reg);
4745 RegNumMap.
insert(std::make_pair(Reg, PNotSel));
4749 dbgs() <<
"Narrowing the search space by deleting costly formulas\n");
4752 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4753 LSRUse &LU = Uses[LUIdx];
4755 if (LU.Formulae.size() < 2)
4760 float FMinRegNum = LU.Formulae[0].getNumRegs();
4761 float FMinARegNum = LU.Formulae[0].getNumRegs();
4763 for (
size_t i = 0,
e = LU.Formulae.size(); i !=
e; ++i) {
4764 Formula &F = LU.Formulae[i];
4767 for (
const SCEV *BaseReg : F.BaseRegs) {
4768 if (UniqRegs.
count(BaseReg))
4770 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4771 if (isa<SCEVAddRecExpr>(BaseReg))
4773 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4775 if (
const SCEV *ScaledReg = F.ScaledReg) {
4776 if (!UniqRegs.
count(ScaledReg)) {
4778 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4779 if (isa<SCEVAddRecExpr>(ScaledReg))
4781 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4784 if (FMinRegNum > FRegNum ||
4785 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4786 FMinRegNum = FRegNum;
4787 FMinARegNum = FARegNum;
4792 dbgs() <<
" with min reg num " << FMinRegNum <<
'\n');
4794 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4795 while (LU.Formulae.size() != 1) {
4798 LU.Formulae.pop_back();
4800 LU.RecomputeRegs(LUIdx, RegUses);
4801 assert(LU.Formulae.size() == 1 &&
"Should be exactly 1 min regs formula");
4802 Formula &F = LU.Formulae[0];
4805 UniqRegs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
4807 UniqRegs.
insert(F.ScaledReg);
4815 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4826 const SCEV *Best =
nullptr;
4827 unsigned BestNum = 0;
4828 for (
const SCEV *Reg : RegUses) {
4829 if (Taken.
count(Reg))
4833 BestNum = RegUses.getUsedByIndices(Reg).count();
4835 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4836 if (Count > BestNum) {
4842 assert(Best &&
"Failed to find best LSRUse candidate");
4844 LLVM_DEBUG(
dbgs() <<
"Narrowing the search space by assuming " << *Best
4845 <<
" will yield profitable reuse.\n");
4850 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4851 LSRUse &LU = Uses[LUIdx];
4852 if (!LU.Regs.count(Best))
continue;
4855 for (
size_t i = 0,
e = LU.Formulae.size(); i !=
e; ++i) {
4856 Formula &F = LU.Formulae[i];
4857 if (!F.referencesReg(Best)) {
4859 LU.DeleteFormula(F);
4863 assert(
e != 0 &&
"Use has no formulae left! Is Regs inconsistent?");
4869 LU.RecomputeRegs(LUIdx, RegUses);
4880 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4881 NarrowSearchSpaceByDetectingSupersets();
4882 NarrowSearchSpaceByCollapsingUnrolledCode();
4883 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4885 NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4887 NarrowSearchSpaceByDeletingCostlyFormulas();
4889 NarrowSearchSpaceByPickingWinnerRegs();
4896 const Cost &CurCost,
4909 const LSRUse &LU = Uses[Workspace.
size()];
4916 for (
const SCEV *S : CurRegs)
4917 if (LU.Regs.count(S))
4921 Cost NewCost(L, SE, TTI);
4922 for (
const Formula &F : LU.Formulae) {
4926 int NumReqRegsToFind = std::min(F.getNumRegs(), ReqRegs.
size());
4927 for (
const SCEV *Reg : ReqRegs) {
4928 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4931 if (NumReqRegsToFind == 0)
4935 if (NumReqRegsToFind != 0) {
4945 NewCost.RateFormula(F, NewRegs, VisitedRegs, LU);
4946 if (NewCost.isLess(SolutionCost)) {
4948 if (Workspace.
size() != Uses.size()) {
4949 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4950 NewRegs, VisitedRegs);
4951 if (F.getNumRegs() == 1 && Workspace.
size() == 1)
4952 VisitedRegs.
insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4955 dbgs() <<
".\nRegs:\n";
4956 for (
const SCEV *S : NewRegs)
dbgs()
4957 <<
"- " << *S <<
"\n";
4960 SolutionCost = NewCost;
4961 Solution = Workspace;
4972 Cost SolutionCost(L, SE, TTI);
4973 SolutionCost.Lose();
4974 Cost CurCost(L, SE, TTI);
4977 Workspace.
reserve(Uses.size());
4980 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4981 CurRegs, VisitedRegs);
4982 if (Solution.
empty()) {
4989 "The chosen solution requires ";
4990 SolutionCost.print(
dbgs());
dbgs() <<
":\n";
4991 for (
size_t i = 0,
e = Uses.size(); i !=
e; ++i) {
4993 Uses[i].print(
dbgs());
4996 Solution[i]->print(
dbgs());
5000 assert(Solution.
size() == Uses.size() &&
"Malformed solution!");
5012 bool AllDominate =
true;
5016 if (isa<CatchSwitchInst>(Tentative))
5020 if (Inst == Tentative || !DT.dominates(Inst, Tentative)) {
5021 AllDominate =
false;
5027 (!BetterPos || !DT.dominates(Inst, BetterPos)))
5037 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
5038 unsigned IPLoopDepth = IPLoop ? IPLoop->
getLoopDepth() : 0;
5041 for (
DomTreeNode *Rung = DT.getNode(IP->getParent()); ; ) {
5042 if (!Rung)
return IP;
5043 Rung = Rung->getIDom();
5044 if (!Rung)
return IP;
5045 IDom = Rung->getBlock();
5048 const Loop *IDomLoop = LI.getLoopFor(IDom);
5049 unsigned IDomDepth = IDomLoop ? IDomLoop->
getLoopDepth() : 0;
5050 if (IDomDepth <= IPLoopDepth &&
5051 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
5072 if (
Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
5074 if (LU.Kind == LSRUse::ICmpZero)
5076 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
5078 if (LF.PostIncLoops.count(L)) {
5079 if (LF.isUseFullyOutsideLoop(L))
5086 for (
const Loop *PIL : LF.PostIncLoops) {
5087 if (PIL == L)
continue;
5092 if (!ExitingBlocks.
empty()) {
5094 for (
unsigned i = 1,
e = ExitingBlocks.
size(); i !=
e; ++i)
5095 BB = DT.findNearestCommonDominator(BB, ExitingBlocks[i]);
5100 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
5101 && !isa<DbgInfoIntrinsic>(LowestIP) &&
5102 "Insertion point must be a normal instruction");
5109 while (isa<PHINode>(IP)) ++IP;
5112 while (IP->isEHPad()) ++IP;
5115 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
5128 Value *LSRInstance::Expand(
const LSRUse &LU,
const LSRFixup &LF,
5132 if (LU.RigidFormula)
5133 return LF.OperandValToReplace;
5137 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
5145 Type *OpTy = LF.OperandValToReplace->getType();
5147 Type *Ty = F.getType();
5161 for (
const SCEV *Reg : F.BaseRegs) {
5162 assert(!Reg->
isZero() &&
"Zero allocated in a base register!");
5170 Value *ICmpScaledV =
nullptr;
5172 const SCEV *ScaledS = F.ScaledReg;
5178 if (LU.Kind == LSRUse::ICmpZero) {
5188 "The only scale supported by ICmpZero uses is -1!");
5231 int64_t
Offset = (uint64_t)F.BaseOffset + LF.Offset;
5233 if (LU.Kind == LSRUse::ICmpZero) {
5250 int64_t UnfoldedOffset = F.UnfoldedOffset;
5251 if (UnfoldedOffset != 0) {
5269 if (LU.Kind == LSRUse::ICmpZero) {
5270 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
5272 assert(!F.BaseGV &&
"ICmp does not support folding a global value and " 5273 "a scale at the same time!");
5274 if (F.Scale == -1) {
5275 if (ICmpScaledV->
getType() != OpTy) {
5279 ICmpScaledV, OpTy,
"tmp", CI);
5286 assert((F.Scale == 0 || F.Scale == 1) &&
5287 "ICmp does not support folding a global value and " 5288 "a scale at the same time!");
5306 void LSRInstance::RewriteForPHI(
5307 PHINode *PN,
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
5312 bool needUpdateFixups =
false;
5323 Loop *PNLoop = LI.getLoopFor(Parent);
5324 if (!PNLoop || Parent != PNLoop->
getHeader()) {
5330 .setMergeIdenticalEdges()
5331 .setKeepOneInputPHIs());
5352 needUpdateFixups =
true;
5357 std::pair<DenseMap<BasicBlock *, Value *>::iterator,
bool> Pair =
5358 Inserted.
insert(std::make_pair(BB, static_cast<Value *>(
nullptr)));
5366 Type *OpTy = LF.OperandValToReplace->getType();
5371 FullV, LF.OperandValToReplace->getType(),
5375 Pair.first->second = FullV;
5382 if (needUpdateFixups) {
5383 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5388 if (
Fixup.UserInst == PN) {
5391 bool foundInOriginalPHI =
false;
5393 if (val ==
Fixup.OperandValToReplace) {
5394 foundInOriginalPHI =
true;
5399 if (foundInOriginalPHI)
5405 for (
const auto &Block : PN->
blocks())
5410 if (val ==
Fixup.OperandValToReplace)
5411 Fixup.UserInst = NewPN;
5421 void LSRInstance::Rewrite(
const LSRUse &LU,
const LSRFixup &LF,
5426 if (
PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
5427 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
5430 Expand(LU, LF, F, LF.UserInst->getIterator(),
Rewriter, DeadInsts);
5433 Type *OpTy = LF.OperandValToReplace->getType();
5434 if (FullV->
getType() != OpTy) {
5437 FullV, OpTy,
"tmp", LF.UserInst);
5446 if (LU.Kind == LSRUse::ICmpZero)
5447 LF.UserInst->setOperand(0, FullV);
5449 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5457 void LSRInstance::ImplementSolution(
5473 for (
const IVChain &Chain : IVChainVec) {
5474 if (
PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
5479 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5480 for (
const LSRFixup &
Fixup : Uses[LUIdx].
Fixups) {
5481 Rewrite(Uses[LUIdx],
Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5485 for (
const IVChain &Chain : IVChainVec) {
5486 GenerateIVChain(Chain, Rewriter, DeadInsts);
5500 : IU(IU), SE(SE), DT(DT), LI(LI), AC(AC), LibInfo(LibInfo), TTI(TTI), L(L),
5508 if (IU.
empty())
return;
5512 unsigned NumUsers = 0;
5514 if (++NumUsers > MaxIVUsers) {
5516 LLVM_DEBUG(
dbgs() <<
"LSR skipping loop, too many IV Users in " << U
5523 if (
auto *PN = dyn_cast<PHINode>(U.getUser())) {
5525 if (isa<FuncletPadInst>(FirstNonPHI) ||
5526 isa<CatchSwitchInst>(FirstNonPHI))
5528 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5541 Rung; Rung = Rung->
getIDom()) {
5544 if (DomLoop && DomLoop->
getHeader() == BB) {
5556 OptimizeLoopTermCond();
5559 if (IU.empty())
return;
5569 CollectInterestingTypesAndFactors();
5570 CollectFixupsAndInitialFormulae();
5571 CollectLoopInvariantFixupsAndFormulae();
5577 print_uses(
dbgs()));
5581 GenerateAllReuseFormulae();
5583 FilterOutUndesirableDedicatedRegisters();
5584 NarrowSearchSpaceUsingHeuristics();
5594 if (Solution.
empty())
5599 for (
const LSRUse &LU : Uses) {
5600 for (
const Formula &F : LU.Formulae)
5602 F) &&
"Illegal formula generated!");
5607 ImplementSolution(Solution);
5610 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP) 5611 void LSRInstance::print_factors_and_types(
raw_ostream &OS)
const {
5612 if (Factors.empty() && Types.empty())
return;
5614 OS <<
"LSR has identified the following interesting factors and types: ";
5617 for (int64_t Factor : Factors) {
5618 if (!First) OS <<
", ";
5620 OS <<
'*' << Factor;
5623 for (
Type *Ty : Types) {
5624 if (!First) OS <<
", ";
5626 OS <<
'(' << *Ty <<
')';
5631 void LSRInstance::print_fixups(
raw_ostream &OS)
const {
5632 OS <<
"LSR is examining the following fixup sites:\n";
5633 for (
const LSRUse &LU : Uses)
5634 for (
const LSRFixup &LF : LU.Fixups) {
5641 void LSRInstance::print_uses(
raw_ostream &OS)
const {
5642 OS <<
"LSR is examining the following uses:\n";
5643 for (
const LSRUse &LU : Uses) {
5647 for (
const Formula &F : LU.Formulae) {
5656 print_factors_and_types(OS);
5668 class LoopStrengthReduce :
public LoopPass {
5672 LoopStrengthReduce();
5681 LoopStrengthReduce::LoopStrengthReduce() :
LoopPass(
ID) {
5685 void LoopStrengthReduce::getAnalysisUsage(
AnalysisUsage &AU)
const {
5713 bool Changed =
false;
5716 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI, AC, LibInfo).getChanged();
5741 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5742 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5743 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5744 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5745 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5747 auto &AC = getAnalysis<AssumptionCacheTracker>().getAssumptionCache(
5749 auto &LibInfo = getAnalysis<TargetLibraryInfoWrapperPass>().getTLI(
5767 "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.
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.
reference emplace_back(ArgTypes &&... Args)
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.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
uint64_t getZExtValue() const
Get zero extended value.
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)
This class represents lattice values for constants.
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
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.
size_t getNumOperands() const
Implements a dense probed hash-table based set.
unsigned getLoopDepth() const
Return the nesting level of this loop.
void push_back(const T &Elt)
static cl::opt< unsigned > ComplexityLimit("lsr-complexity-limit", cl::Hidden, cl::init(std::numeric_limits< uint16_t >::max()), cl::desc("LSR search space complexity limit"))
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.
An immutable pass that tracks lazily created AssumptionCache objects.
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
A cache of @llvm.assume calls within a function.
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)
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)
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.
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
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
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...
unsigned 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...
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
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...
static unsigned getSetupCost(const SCEV *Reg, unsigned Depth)
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: ...
int64_t getSExtValue() const
Get sign extended value.
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.
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.
BasicBlock * SplitCriticalEdge(Instruction *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
AnalysisUsage & addPreservedID(const void *ID)
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.
static bool isProfitableChain(IVChain &Chain, SmallPtrSetImpl< Instruction *> &Users, ScalarEvolution &SE)
Return true if the number of registers needed for the chain is estimated to be less than the number r...
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.
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.
unsigned getNumSuccessors() const
Return the number of successors that this instruction has.
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...
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock *> Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock *> &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, MemorySSAUpdater *MSSAU=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
iterator find(const_arg_type_t< KeyT > Val)
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 ...
static bool isCompatibleIVType(Value *LVal, Value *RVal)
Return true if we allow an IV chain to include both types.
bool isNegative() const
Determine sign of this APInt.
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
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
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.
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.
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
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 cl::opt< unsigned > SetupCostDepthLimit("lsr-setupcost-depth-limit", cl::Hidden, cl::init(7), cl::desc("The limit on recursion depth for LSRs setup cost"))
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...
static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, LoopInfo &LI, const TargetTransformInfo &TTI, AssumptionCache &AC, TargetLibraryInfo &LibInfo)
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.
Align max(MaybeAlign Lhs, Align Rhs)
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)
static uint64_t add(uint64_t LeftOp, uint64_t RightOp)
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Module.h This file contains the declarations for the Module class.
Provides information about what library functions are available for the current target.
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()
InstListType::iterator iterator
Instruction iterators...
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.
const SCEV * getBackedgeTakenCount(const Loop *L, ExitCountKind Kind=Exact)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
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)
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
static cl::opt< bool > EnableBackedgeIndexing("lsr-backedge-indexing", cl::Hidden, cl::init(true), cl::desc("Enable the generation of cross iteration indexed memops"))
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.
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.
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 isEqual(const GCNRPTracker::LiveRegSet &S1, const GCNRPTracker::LiveRegSet &S2)
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 ...
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)
op_range incoming_values()
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...
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.