114 using namespace llvm;
116 #define DEBUG_TYPE "loop-reduce"
130 cl::desc(
"Enable LSR phi elimination"));
135 cl::desc(
"Add instruction count to a LSR cost model"));
140 cl::desc(
"Narrow LSR complex solution using"
141 " expectation of registers number"));
147 cl::desc(
"Narrow LSR search space by filtering non-optimal formulae"
148 " with the same ScaledReg and Scale"));
154 cl::desc(
"Stress test LSR IV chains"));
163 static const unsigned UnknownAddressSpace = ~0u;
168 MemAccessTy() : MemTy(nullptr), AddrSpace(UnknownAddressSpace) {}
170 MemAccessTy(
Type *Ty,
unsigned AS) :
171 MemTy(Ty), AddrSpace(AS) {}
174 return MemTy == Other.MemTy && AddrSpace == Other.AddrSpace;
177 bool operator!=(MemAccessTy Other)
const {
return !(*
this == Other); }
180 unsigned AS = UnknownAddressSpace) {
199 OS <<
"[NumUses=" << UsedByIndices.count() <<
']';
202 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
211 class RegUseTracker {
214 RegUsesTy RegUsesMap;
218 void countRegister(
const SCEV *
Reg,
size_t LUIdx);
219 void dropRegister(
const SCEV *
Reg,
size_t LUIdx);
220 void swapAndDropUse(
size_t LUIdx,
size_t LastLUIdx);
222 bool isRegUsedByUsesOtherThan(
const SCEV *
Reg,
size_t LUIdx)
const;
239 RegUseTracker::countRegister(
const SCEV *
Reg,
size_t LUIdx) {
240 std::pair<RegUsesTy::iterator, bool> Pair =
241 RegUsesMap.insert(std::make_pair(Reg, RegSortData()));
242 RegSortData &RSD = Pair.first->second;
245 RSD.UsedByIndices.resize(
std::max(RSD.UsedByIndices.size(), LUIdx + 1));
246 RSD.UsedByIndices.set(LUIdx);
250 RegUseTracker::dropRegister(
const SCEV *Reg,
size_t LUIdx) {
251 RegUsesTy::iterator It = RegUsesMap.find(Reg);
252 assert(It != RegUsesMap.end());
253 RegSortData &RSD = It->second;
254 assert(RSD.UsedByIndices.size() > LUIdx);
255 RSD.UsedByIndices.reset(LUIdx);
259 RegUseTracker::swapAndDropUse(
size_t LUIdx,
size_t LastLUIdx) {
260 assert(LUIdx <= LastLUIdx);
264 for (
auto &Pair : RegUsesMap) {
266 if (LUIdx < UsedByIndices.
size())
267 UsedByIndices[LUIdx] =
268 LastLUIdx < UsedByIndices.
size() ? UsedByIndices[LastLUIdx] :
false;
274 RegUseTracker::isRegUsedByUsesOtherThan(
const SCEV *Reg,
size_t LUIdx)
const {
275 RegUsesTy::const_iterator
I = RegUsesMap.find(Reg);
276 if (I == RegUsesMap.end())
280 if (i == -1)
return false;
281 if ((
size_t)i != LUIdx)
return true;
286 RegUsesTy::const_iterator I = RegUsesMap.find(Reg);
287 assert(I != RegUsesMap.end() &&
"Unknown register!");
288 return I->second.UsedByIndices;
331 const SCEV *ScaledReg;
336 int64_t UnfoldedOffset;
339 : BaseGV(nullptr), BaseOffset(0), HasBaseReg(
false), Scale(0),
340 ScaledReg(nullptr), UnfoldedOffset(0) {}
346 void canonicalize(
const Loop &
L);
350 bool hasZeroEnd()
const;
352 size_t getNumRegs()
const;
355 void deleteBaseReg(
const SCEV *&S);
357 bool referencesReg(
const SCEV *S)
const;
358 bool hasRegsUsedByUsesOtherThan(
size_t LUIdx,
359 const RegUseTracker &RegUses)
const;
380 for (
const SCEV *S :
Add->operands())
387 if (!AR->getStart()->isZero() && AR->isAffine()) {
390 AR->getStepRecurrence(SE),
398 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S))
399 if (Mul->getOperand(0)->isAllOnesValue()) {
408 for (
const SCEV *S : MyGood)
410 for (
const SCEV *S : MyBad)
429 BaseRegs.push_back(Sum);
435 BaseRegs.push_back(Sum);
446 return BaseRegs.size() <= 1;
451 if (Scale == 1 && BaseRegs.empty())
463 return isa<const SCEVAddRecExpr>(S) &&
464 (cast<SCEVAddRecExpr>(S)->getLoop() == &
L);
466 return I == BaseRegs.end();
475 void Formula::canonicalize(
const Loop &L) {
480 assert(!BaseRegs.empty() &&
"1*reg => reg, should not be needed.");
484 ScaledReg = BaseRegs.back();
496 return isa<const SCEVAddRecExpr>(S) &&
497 (cast<SCEVAddRecExpr>(S)->getLoop() == &
L);
499 if (I != BaseRegs.end())
508 bool Formula::unscale() {
512 BaseRegs.push_back(ScaledReg);
517 bool Formula::hasZeroEnd()
const {
518 if (UnfoldedOffset || BaseOffset)
520 if (BaseRegs.size() != 1 || ScaledReg)
527 size_t Formula::getNumRegs()
const {
528 return !!ScaledReg + BaseRegs.size();
534 return !BaseRegs.empty() ? BaseRegs.front()->getType() :
535 ScaledReg ? ScaledReg->getType() :
536 BaseGV ? BaseGV->getType() :
541 void Formula::deleteBaseReg(
const SCEV *&S) {
542 if (&S != &BaseRegs.back())
548 bool Formula::referencesReg(
const SCEV *S)
const {
554 bool Formula::hasRegsUsedByUsesOtherThan(
size_t LUIdx,
555 const RegUseTracker &RegUses)
const {
557 if (RegUses.isRegUsedByUsesOtherThan(ScaledReg, LUIdx))
559 for (
const SCEV *BaseReg : BaseRegs)
560 if (RegUses.isRegUsedByUsesOtherThan(BaseReg, LUIdx))
568 if (!First) OS <<
" + ";
else First =
false;
569 BaseGV->printAsOperand(OS,
false);
571 if (BaseOffset != 0) {
572 if (!First) OS <<
" + ";
else First =
false;
575 for (
const SCEV *BaseReg : BaseRegs) {
576 if (!First) OS <<
" + ";
else First =
false;
577 OS <<
"reg(" << *BaseReg <<
')';
579 if (HasBaseReg && BaseRegs.empty()) {
580 if (!First) OS <<
" + ";
else First =
false;
581 OS <<
"**error: HasBaseReg**";
582 }
else if (!HasBaseReg && !BaseRegs.empty()) {
583 if (!First) OS <<
" + ";
else First =
false;
584 OS <<
"**error: !HasBaseReg**";
587 if (!First) OS <<
" + ";
else First =
false;
588 OS << Scale <<
"*reg(";
595 if (UnfoldedOffset != 0) {
596 if (!First) OS <<
" + ";
597 OS <<
"imm(" << UnfoldedOffset <<
')';
601 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
639 bool IgnoreSignificantBits =
false) {
661 const APInt &LA =
C->getAPInt();
663 if (LA.
srem(RA) != 0)
670 if ((IgnoreSignificantBits ||
isAddRecSExtable(AR, SE)) && AR->isAffine()) {
672 IgnoreSignificantBits);
673 if (!Step)
return nullptr;
675 IgnoreSignificantBits);
676 if (!Start)
return nullptr;
689 for (
const SCEV *S :
Add->operands()) {
691 if (!Op)
return nullptr;
700 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(LHS)) {
704 for (
const SCEV *S : Mul->operands()) {
707 IgnoreSignificantBits)) {
726 if (
C->getAPInt().getMinSignedBits() <= 64) {
728 return C->getValue()->getSExtValue();
736 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
751 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(S)) {
752 if (
GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue())) {
762 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
777 bool isAddress = isa<LoadInst>(Inst);
779 if (
SI->getPointerOperand() == OperandVal)
781 }
else if (
IntrinsicInst *II = dyn_cast<IntrinsicInst>(Inst)) {
784 switch (II->getIntrinsicID()) {
787 if (II->getArgOperand(0) == OperandVal)
791 }
else if (
AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
792 if (RMW->getPointerOperand() == OperandVal)
795 if (CmpX->getPointerOperand() == OperandVal)
803 MemAccessTy AccessTy(Inst->
getType(), MemAccessTy::UnknownAddressSpace);
804 if (
const StoreInst *
SI = dyn_cast<StoreInst>(Inst)) {
805 AccessTy.MemTy =
SI->getOperand(0)->getType();
806 AccessTy.AddrSpace =
SI->getPointerAddressSpace();
807 }
else if (
const LoadInst *LI = dyn_cast<LoadInst>(Inst)) {
808 AccessTy.AddrSpace = LI->getPointerAddressSpace();
809 }
else if (
const AtomicRMWInst *RMW = dyn_cast<AtomicRMWInst>(Inst)) {
810 AccessTy.AddrSpace = RMW->getPointerAddressSpace();
812 AccessTy.AddrSpace = CmpX->getPointerAddressSpace();
817 if (
PointerType *PTy = dyn_cast<PointerType>(AccessTy.MemTy))
819 PTy->getAddressSpace());
865 if (!Processed.
insert(S).second)
869 for (
const SCEV *S :
Add->operands()) {
876 if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
877 if (Mul->getNumOperands() == 2) {
879 if (isa<SCEVConstant>(Mul->getOperand(0)))
884 if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(Mul->getOperand(1))) {
885 Value *UVal = U->getValue();
889 if (UI && UI->
getOpcode() == Instruction::Mul &&
911 bool Changed =
false;
913 while (!DeadInsts.
empty()) {
950 const LSRUse &LU,
const Formula &
F);
953 const LSRUse &LU,
const Formula &
F,
981 return ((
C.Insns |
C.NumRegs |
C.AddRecCost |
C.NumIVMuls |
C.NumBaseAdds
982 |
C.ImmCost |
C.SetupCost |
C.ScaleCost) != ~0u)
983 || ((
C.Insns &
C.NumRegs &
C.AddRecCost &
C.NumIVMuls &
C.NumBaseAdds
984 &
C.ImmCost &
C.SetupCost &
C.ScaleCost) == ~0u);
990 return C.NumRegs == ~0u;
1006 void RateRegister(
const SCEV *Reg,
1010 void RatePrimaryRegister(
const SCEV *Reg,
1025 Value *OperandValToReplace;
1037 bool isUseFullyOutsideLoop(
const Loop *L)
const;
1047 struct UniquifierDenseMapInfo {
1050 V.
push_back(reinterpret_cast<const SCEV *>(-1));
1056 V.
push_back(reinterpret_cast<const SCEV *>(-2));
1092 MemAccessTy AccessTy;
1103 bool AllFixupsOutsideLoop;
1116 Type *WidestFixupType;
1126 LSRUse(KindType K, MemAccessTy AT)
1127 :
Kind(K), AccessTy(AT), MinOffset(INT64_MAX), MaxOffset(INT64_MIN),
1128 AllFixupsOutsideLoop(
true), RigidFormula(
false),
1129 WidestFixupType(nullptr) {}
1131 LSRFixup &getNewFixup() {
1132 Fixups.push_back(LSRFixup());
1136 void pushFixup(LSRFixup &f) {
1138 if (f.Offset > MaxOffset)
1139 MaxOffset = f.Offset;
1140 if (f.Offset < MinOffset)
1141 MinOffset = f.Offset;
1144 bool HasFormulaWithSameRegs(
const Formula &
F)
const;
1145 float getNotSelectedProbability(
const SCEV *Reg)
const;
1146 bool InsertFormula(
const Formula &
F,
const Loop &L);
1147 void DeleteFormula(Formula &
F);
1148 void RecomputeRegs(
size_t LUIdx, RegUseTracker &Reguses);
1157 void Cost::RateRegister(
const SCEV *Reg,
1165 if (AR->getLoop() !=
L) {
1172 if (!AR->getLoop()->contains(L)) {
1185 if (!AR->isAffine() || !isa<SCEVConstant>(AR->getOperand(1))) {
1186 if (!Regs.
count(AR->getOperand(1))) {
1187 RateRegister(AR->getOperand(1),
Regs,
L, SE, DT);
1197 if (!isa<SCEVUnknown>(Reg) &&
1198 !isa<SCEVConstant>(
Reg) &&
1199 !(isa<SCEVAddRecExpr>(Reg) &&
1200 (isa<SCEVUnknown>(cast<SCEVAddRecExpr>(
Reg)->getStart()) ||
1201 isa<SCEVConstant>(cast<SCEVAddRecExpr>(Reg)->getStart()))))
1204 C.NumIVMuls += isa<SCEVMulExpr>(
Reg) &&
1211 void Cost::RatePrimaryRegister(
const SCEV *Reg,
1216 if (LoserRegs && LoserRegs->
count(Reg)) {
1220 if (Regs.
insert(Reg).second) {
1221 RateRegister(Reg, Regs, L, SE, DT);
1222 if (LoserRegs && isLoser())
1235 assert(F.isCanonical(*L) &&
"Cost is accurate only for canonical formula");
1237 unsigned PrevAddRecCost =
C.AddRecCost;
1238 unsigned PrevNumRegs =
C.NumRegs;
1239 unsigned PrevNumBaseAdds =
C.NumBaseAdds;
1240 if (
const SCEV *ScaledReg = F.ScaledReg) {
1241 if (VisitedRegs.
count(ScaledReg)) {
1245 RatePrimaryRegister(ScaledReg, Regs, L, SE, DT, LoserRegs);
1249 for (
const SCEV *BaseReg : F.BaseRegs) {
1250 if (VisitedRegs.
count(BaseReg)) {
1254 RatePrimaryRegister(BaseReg, Regs, L, SE, DT, LoserRegs);
1260 size_t NumBaseParts = F.getNumRegs();
1261 if (NumBaseParts > 1)
1266 C.NumBaseAdds += (F.UnfoldedOffset != 0);
1272 for (
const LSRFixup &Fixup : LU.Fixups) {
1273 int64_t O = Fixup.Offset;
1274 int64_t
Offset = (uint64_t)O + F.BaseOffset;
1278 else if (Offset != 0)
1283 if ((isa<LoadInst>(Fixup.UserInst) || isa<StoreInst>(Fixup.UserInst)) &&
1297 if (
C.NumRegs > TTIRegNum) {
1300 if (PrevNumRegs > TTIRegNum)
1301 C.Insns += (
C.NumRegs - PrevNumRegs);
1303 C.Insns += (
C.NumRegs - TTIRegNum);
1315 if (LU.Kind == LSRUse::ICmpZero && !F.hasZeroEnd())
1318 C.Insns += (
C.AddRecCost - PrevAddRecCost);
1321 if (LU.Kind != LSRUse::ICmpZero)
1322 C.Insns +=
C.NumBaseAdds - PrevNumBaseAdds;
1332 C.NumBaseAdds = ~0u;
1341 C.Insns != Other.C.Insns)
1342 return C.Insns < Other.C.Insns;
1348 OS <<
C.Insns <<
" instruction" << (
C.Insns == 1 ?
" " :
"s ");
1349 OS <<
C.NumRegs <<
" reg" << (
C.NumRegs == 1 ?
"" :
"s");
1350 if (
C.AddRecCost != 0)
1351 OS <<
", with addrec cost " <<
C.AddRecCost;
1352 if (
C.NumIVMuls != 0)
1353 OS <<
", plus " <<
C.NumIVMuls <<
" IV mul"
1354 << (
C.NumIVMuls == 1 ?
"" :
"s");
1355 if (
C.NumBaseAdds != 0)
1356 OS <<
", plus " <<
C.NumBaseAdds <<
" base add"
1357 << (
C.NumBaseAdds == 1 ?
"" :
"s");
1358 if (
C.ScaleCost != 0)
1359 OS <<
", plus " <<
C.ScaleCost <<
" scale cost";
1361 OS <<
", plus " <<
C.ImmCost <<
" imm cost";
1362 if (
C.SetupCost != 0)
1363 OS <<
", plus " <<
C.SetupCost <<
" setup cost";
1366 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1372 LSRFixup::LSRFixup()
1373 : UserInst(nullptr), OperandValToReplace(nullptr),
1377 bool LSRFixup::isUseFullyOutsideLoop(
const Loop *L)
const {
1379 if (
const PHINode *PN = dyn_cast<PHINode>(UserInst)) {
1380 for (
unsigned i = 0, e = PN->getNumIncomingValues(); i != e; ++i)
1381 if (PN->getIncomingValue(i) == OperandValToReplace &&
1382 L->
contains(PN->getIncomingBlock(i)))
1395 Store->getOperand(0)->printAsOperand(OS,
false);
1396 }
else if (UserInst->getType()->isVoidTy())
1397 OS << UserInst->getOpcodeName();
1399 UserInst->printAsOperand(OS,
false);
1401 OS <<
", OperandValToReplace=";
1402 OperandValToReplace->printAsOperand(OS,
false);
1404 for (
const Loop *PIL : PostIncLoops) {
1405 OS <<
", PostIncLoop=";
1406 PIL->getHeader()->printAsOperand(OS,
false);
1410 OS <<
", Offset=" <<
Offset;
1413 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1421 bool LSRUse::HasFormulaWithSameRegs(
const Formula &F)
const {
1423 if (F.ScaledReg) Key.
push_back(F.ScaledReg);
1426 return Uniquifier.count(Key);
1430 float LSRUse::getNotSelectedProbability(
const SCEV *Reg)
const {
1432 for (
const Formula &F : Formulae)
1433 if (F.referencesReg(Reg))
1435 return ((
float)(Formulae.size() - FNum)) / Formulae.size();
1440 bool LSRUse::InsertFormula(
const Formula &F,
const Loop &L) {
1441 assert(F.isCanonical(L) &&
"Invalid canonical representation");
1443 if (!Formulae.empty() && RigidFormula)
1447 if (F.ScaledReg) Key.
push_back(F.ScaledReg);
1451 if (!Uniquifier.insert(Key).second)
1455 assert((!F.ScaledReg || !F.ScaledReg->isZero()) &&
1456 "Zero allocated in a scaled register!");
1458 for (
const SCEV *BaseReg : F.BaseRegs)
1459 assert(!BaseReg->
isZero() &&
"Zero allocated in a base register!");
1463 Formulae.push_back(F);
1466 Regs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
1468 Regs.
insert(F.ScaledReg);
1474 void LSRUse::DeleteFormula(Formula &F) {
1475 if (&F != &Formulae.back())
1477 Formulae.pop_back();
1481 void LSRUse::RecomputeRegs(
size_t LUIdx, RegUseTracker &RegUses) {
1485 for (
const Formula &F : Formulae) {
1486 if (F.ScaledReg) Regs.
insert(F.ScaledReg);
1487 Regs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
1491 for (
const SCEV *S : OldRegs)
1493 RegUses.dropRegister(S, LUIdx);
1497 OS <<
"LSR Use: Kind=";
1499 case Basic: OS <<
"Basic";
break;
1500 case Special: OS <<
"Special";
break;
1501 case ICmpZero: OS <<
"ICmpZero";
break;
1503 OS <<
"Address of ";
1504 if (AccessTy.MemTy->isPointerTy())
1507 OS << *AccessTy.MemTy;
1510 OS <<
" in addrspace(" << AccessTy.AddrSpace <<
')';
1513 OS <<
", Offsets={";
1514 bool NeedComma =
false;
1515 for (
const LSRFixup &Fixup :
Fixups) {
1516 if (NeedComma) OS <<
',';
1522 if (AllFixupsOutsideLoop)
1523 OS <<
", all-fixups-outside-loop";
1525 if (WidestFixupType)
1526 OS <<
", widest fixup type: " << *WidestFixupType;
1529 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
1536 LSRUse::KindType
Kind, MemAccessTy AccessTy,
1538 bool HasBaseReg, int64_t Scale) {
1542 HasBaseReg, Scale, AccessTy.AddrSpace);
1544 case LSRUse::ICmpZero:
1551 if (Scale != 0 && HasBaseReg && BaseOffset != 0)
1556 if (Scale != 0 && Scale != -1)
1561 if (BaseOffset != 0) {
1568 BaseOffset = -(uint64_t)BaseOffset;
1577 return !BaseGV && Scale == 0 && BaseOffset == 0;
1579 case LSRUse::Special:
1581 return !BaseGV && (Scale == 0 || Scale == -1) && BaseOffset == 0;
1588 int64_t MinOffset, int64_t MaxOffset,
1589 LSRUse::KindType
Kind, MemAccessTy AccessTy,
1591 bool HasBaseReg, int64_t Scale) {
1593 if (((int64_t)((uint64_t)BaseOffset + MinOffset) > BaseOffset) !=
1596 MinOffset = (uint64_t)BaseOffset + MinOffset;
1597 if (((int64_t)((uint64_t)BaseOffset + MaxOffset) > BaseOffset) !=
1600 MaxOffset = (uint64_t)BaseOffset + MaxOffset;
1603 HasBaseReg, Scale) &&
1609 int64_t MinOffset, int64_t MaxOffset,
1610 LSRUse::KindType
Kind, MemAccessTy AccessTy,
1611 const Formula &F,
const Loop &L) {
1619 assert((F.isCanonical(L) || F.Scale != 0));
1621 F.BaseGV, F.BaseOffset, F.HasBaseReg, F.Scale);
1626 int64_t MaxOffset, LSRUse::KindType
Kind,
1628 int64_t BaseOffset,
bool HasBaseReg, int64_t Scale) {
1631 BaseOffset, HasBaseReg, Scale) ||
1636 BaseGV, BaseOffset,
true, 0));
1640 int64_t MaxOffset, LSRUse::KindType
Kind,
1641 MemAccessTy AccessTy,
const Formula &F) {
1642 return isLegalUse(TTI, MinOffset, MaxOffset, Kind, AccessTy, F.BaseGV,
1643 F.BaseOffset, F.HasBaseReg, F.Scale);
1647 const LSRUse &LU,
const Formula &F) {
1649 LU.AccessTy, F.BaseGV, F.BaseOffset, F.HasBaseReg,
1654 const LSRUse &LU,
const Formula &F,
1663 return F.Scale != 1;
1669 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MinOffset, F.HasBaseReg,
1670 F.Scale, LU.AccessTy.AddrSpace);
1672 LU.AccessTy.MemTy, F.BaseGV, F.BaseOffset + LU.MaxOffset, F.HasBaseReg,
1673 F.Scale, LU.AccessTy.AddrSpace);
1675 assert(ScaleCostMinOffset >= 0 && ScaleCostMaxOffset >= 0 &&
1676 "Legal addressing mode has an illegal cost!");
1677 return std::max(ScaleCostMinOffset, ScaleCostMaxOffset);
1679 case LSRUse::ICmpZero:
1681 case LSRUse::Special:
1691 LSRUse::KindType
Kind, MemAccessTy AccessTy,
1695 if (BaseOffset == 0 && !BaseGV)
return true;
1699 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1703 if (!HasBaseReg && Scale == 1) {
1714 int64_t MaxOffset, LSRUse::KindType
Kind,
1715 MemAccessTy AccessTy,
const SCEV *S,
1718 if (S->
isZero())
return true;
1726 if (!S->
isZero())
return false;
1729 if (BaseOffset == 0 && !BaseGV)
return true;
1733 int64_t Scale = Kind == LSRUse::ICmpZero ? -1 : 1;
1736 BaseOffset, HasBaseReg, Scale);
1753 const SCEV *IncExpr;
1756 UserInst(U), IVOperand(O), IncExpr(E) {}
1763 const SCEV *ExprBase;
1765 IVChain() : ExprBase(nullptr) {}
1767 IVChain(
const IVInc &Head,
const SCEV *
Base)
1768 : Incs(1, Head), ExprBase(Base) {}
1773 const_iterator
begin()
const {
1775 return std::next(Incs.begin());
1777 const_iterator
end()
const {
1782 bool hasIncs()
const {
return Incs.size() >= 2; }
1785 void add(
const IVInc &
X) { Incs.push_back(X); }
1788 Instruction *tailUserInst()
const {
return Incs.back().UserInst; }
1791 bool isProfitableIncrement(
const SCEV *OperExpr,
1792 const SCEV *IncExpr,
1835 RegUseTracker RegUses;
1840 static const unsigned MaxChains = 8;
1848 void OptimizeShadowIV();
1851 void OptimizeLoopTermCond();
1855 void FinalizeChain(IVChain &Chain);
1856 void CollectChains();
1860 void CollectInterestingTypesAndFactors();
1861 void CollectFixupsAndInitialFormulae();
1867 bool reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
bool HasBaseReg,
1868 LSRUse::KindType
Kind, MemAccessTy AccessTy);
1870 std::pair<size_t, int64_t> getUse(
const SCEV *&Expr, LSRUse::KindType
Kind,
1871 MemAccessTy AccessTy);
1873 void DeleteUse(LSRUse &LU,
size_t LUIdx);
1875 LSRUse *FindUseWithSimilarFormula(
const Formula &F,
const LSRUse &OrigLU);
1877 void InsertInitialFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx);
1878 void InsertSupplementalFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx);
1879 void CountRegisters(
const Formula &F,
size_t LUIdx);
1880 bool InsertFormula(LSRUse &LU,
unsigned LUIdx,
const Formula &F);
1882 void CollectLoopInvariantFixupsAndFormulae();
1884 void GenerateReassociations(LSRUse &LU,
unsigned LUIdx, Formula
Base,
1885 unsigned Depth = 0);
1887 void GenerateReassociationsImpl(LSRUse &LU,
unsigned LUIdx,
1889 size_t Idx,
bool IsScaledReg =
false);
1890 void GenerateCombinations(LSRUse &LU,
unsigned LUIdx, Formula
Base);
1891 void GenerateSymbolicOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
1892 const Formula &
Base,
size_t Idx,
1893 bool IsScaledReg =
false);
1894 void GenerateSymbolicOffsets(LSRUse &LU,
unsigned LUIdx, Formula
Base);
1895 void GenerateConstantOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
1896 const Formula &
Base,
1898 size_t Idx,
bool IsScaledReg =
false);
1899 void GenerateConstantOffsets(LSRUse &LU,
unsigned LUIdx, Formula
Base);
1900 void GenerateICmpZeroScales(LSRUse &LU,
unsigned LUIdx, Formula
Base);
1901 void GenerateScales(LSRUse &LU,
unsigned LUIdx, Formula
Base);
1902 void GenerateTruncates(LSRUse &LU,
unsigned LUIdx, Formula
Base);
1903 void GenerateCrossUseConstantOffsets();
1904 void GenerateAllReuseFormulae();
1906 void FilterOutUndesirableDedicatedRegisters();
1908 size_t EstimateSearchSpaceComplexity()
const;
1909 void NarrowSearchSpaceByDetectingSupersets();
1910 void NarrowSearchSpaceByCollapsingUnrolledCode();
1911 void NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
1912 void NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
1913 void NarrowSearchSpaceByDeletingCostlyFormulas();
1914 void NarrowSearchSpaceByPickingWinnerRegs();
1915 void NarrowSearchSpaceUsingHeuristics();
1920 const Cost &CurCost,
1934 Value *Expand(
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
1937 void RewriteForPHI(
PHINode *PN,
const LSRUse &LU,
const LSRFixup &LF,
1940 void Rewrite(
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
1949 bool getChanged()
const {
return Changed; }
1951 void print_factors_and_types(
raw_ostream &OS)
const;
1962 void LSRInstance::OptimizeShadowIV() {
1964 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
1972 Type *DestTy =
nullptr;
1973 bool IsSigned =
false;
1987 if (
UIToFPInst *UCast = dyn_cast<UIToFPInst>(CandidateUI->getUser())) {
1989 DestTy = UCast->getDestTy();
1991 else if (
SIToFPInst *SCast = dyn_cast<SIToFPInst>(CandidateUI->getUser())) {
1993 DestTy = SCast->getDestTy();
1995 if (!DestTy)
continue;
2007 if (Mantissa == -1)
continue;
2011 unsigned Entry, Latch;
2021 if (!Init)
continue;
2022 Constant *NewInit = ConstantFP::get(DestTy, IsSigned ?
2028 if (!Incr)
continue;
2030 && Incr->getOpcode() != Instruction::Sub)
2035 if (Incr->getOperand(0) == PH)
2036 C = dyn_cast<ConstantInt>(Incr->getOperand(1));
2037 else if (Incr->getOperand(1) == PH)
2038 C = dyn_cast<ConstantInt>(Incr->getOperand(0));
2049 PHINode *NewPH = PHINode::Create(DestTy, 2,
"IV.S.", PH);
2055 Instruction::FAdd : Instruction::FSub,
2056 NewPH, CFP,
"IV.S.next.", Incr);
2073 if (U.getUser() == Cond) {
2139 if (!Sel || !Sel->
hasOneUse())
return Cond;
2142 if (isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2147 const SCEV *IterationCount = SE.
getAddExpr(One, BackedgeTakenCount);
2148 if (IterationCount != SE.
getSCEV(Sel))
return Cond;
2155 if (
const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(BackedgeTakenCount)) {
2156 Pred = ICmpInst::ICMP_SLE;
2158 }
else if (
const SCEVSMaxExpr *S = dyn_cast<SCEVSMaxExpr>(IterationCount)) {
2159 Pred = ICmpInst::ICMP_SLT;
2161 }
else if (
const SCEVUMaxExpr *U = dyn_cast<SCEVUMaxExpr>(IterationCount)) {
2162 Pred = ICmpInst::ICMP_ULT;
2193 "Loop condition operand is an addrec in a different loop!");
2197 Value *NewRHS =
nullptr;
2201 if (
ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2202 if (BO1->isOne() && SE.
getSCEV(BO->getOperand(0)) == MaxRHS)
2203 NewRHS = BO->getOperand(0);
2205 if (
ConstantInt *BO1 = dyn_cast<ConstantInt>(BO->getOperand(1)))
2206 if (BO1->isOne() && SE.
getSCEV(BO->getOperand(0)) == MaxRHS)
2207 NewRHS = BO->getOperand(0);
2214 else if (
const SCEVUnknown *SU = dyn_cast<SCEVUnknown>(MaxRHS))
2215 NewRHS = SU->getValue();
2223 Pred = CmpInst::getInversePredicate(Pred);
2243 LSRInstance::OptimizeLoopTermCond() {
2262 return LatchBlock != BB;
2270 for (
BasicBlock *ExitingBlock : ExitingBlocks) {
2287 if (!FindIVUserForCond(Cond, CondUse))
2296 Cond = OptimizeMax(Cond, CondUse);
2301 if (!DT.
dominates(ExitingBlock, LatchBlock))
2306 if (LatchBlock != ExitingBlock)
2310 if (&*UI != CondUse &&
2314 const SCEV *
A = IU.getStride(*CondUse, L);
2315 const SCEV *
B = IU.getStride(*UI, L);
2316 if (!A || !B)
continue;
2326 dyn_cast_or_null<SCEVConstant>(
getExactSDiv(B, A, SE))) {
2330 goto decline_post_inc;
2334 goto decline_post_inc;
2341 AccessTy.AddrSpace))
2342 goto decline_post_inc;
2347 AccessTy.AddrSpace))
2348 goto decline_post_inc;
2352 DEBUG(
dbgs() <<
" Change loop exiting icmp to use postinc iv: "
2364 Cond = cast<ICmpInst>(Cond->
clone());
2366 ExitingBlock->getInstList().insert(TermBr->
getIterator(), Cond);
2393 IVIncInsertPos = Inst;
2394 else if (BB != IVIncInsertPos->
getParent())
2401 bool LSRInstance::reconcileNewOffset(LSRUse &LU, int64_t NewOffset,
2402 bool HasBaseReg, LSRUse::KindType
Kind,
2403 MemAccessTy AccessTy) {
2404 int64_t NewMinOffset = LU.MinOffset;
2405 int64_t NewMaxOffset = LU.MaxOffset;
2406 MemAccessTy NewAccessTy = AccessTy;
2411 if (LU.Kind != Kind)
2418 if (AccessTy.MemTy != LU.AccessTy.MemTy) {
2419 NewAccessTy = MemAccessTy::getUnknown(AccessTy.MemTy->getContext(),
2420 AccessTy.AddrSpace);
2425 if (NewOffset < LU.MinOffset) {
2427 LU.MaxOffset - NewOffset, HasBaseReg))
2429 NewMinOffset = NewOffset;
2430 }
else if (NewOffset > LU.MaxOffset) {
2432 NewOffset - LU.MinOffset, HasBaseReg))
2434 NewMaxOffset = NewOffset;
2438 LU.MinOffset = NewMinOffset;
2439 LU.MaxOffset = NewMaxOffset;
2440 LU.AccessTy = NewAccessTy;
2447 std::pair<size_t, int64_t> LSRInstance::getUse(
const SCEV *&Expr,
2448 LSRUse::KindType Kind,
2449 MemAccessTy AccessTy) {
2460 std::pair<UseMapTy::iterator, bool>
P =
2464 size_t LUIdx = P.first->second;
2465 LSRUse &LU = Uses[LUIdx];
2466 if (reconcileNewOffset(LU, Offset,
true, Kind, AccessTy))
2468 return std::make_pair(LUIdx, Offset);
2472 size_t LUIdx = Uses.size();
2473 P.first->second = LUIdx;
2474 Uses.push_back(LSRUse(Kind, AccessTy));
2475 LSRUse &LU = Uses[LUIdx];
2479 return std::make_pair(LUIdx, Offset);
2483 void LSRInstance::DeleteUse(LSRUse &LU,
size_t LUIdx) {
2484 if (&LU != &Uses.back())
2489 RegUses.swapAndDropUse(LUIdx, Uses.size());
2495 LSRInstance::FindUseWithSimilarFormula(
const Formula &OrigF,
2496 const LSRUse &OrigLU) {
2498 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
2499 LSRUse &LU = Uses[LUIdx];
2505 if (&LU != &OrigLU &&
2506 LU.Kind != LSRUse::ICmpZero &&
2507 LU.Kind == OrigLU.Kind && OrigLU.AccessTy == LU.AccessTy &&
2508 LU.WidestFixupType == OrigLU.WidestFixupType &&
2509 LU.HasFormulaWithSameRegs(OrigF)) {
2511 for (
const Formula &F : LU.Formulae) {
2514 if (F.BaseRegs == OrigF.BaseRegs &&
2515 F.ScaledReg == OrigF.ScaledReg &&
2516 F.BaseGV == OrigF.BaseGV &&
2517 F.Scale == OrigF.Scale &&
2518 F.UnfoldedOffset == OrigF.UnfoldedOffset) {
2519 if (F.BaseOffset == 0)
2534 void LSRInstance::CollectInterestingTypesAndFactors() {
2540 const SCEV *Expr = IU.getExpr(U);
2556 }
while (!Worklist.
empty());
2561 I = Strides.
begin(),
E = Strides.
end(); I !=
E; ++
I)
2563 std::next(I); NewStrideIter !=
E; ++NewStrideIter) {
2564 const SCEV *OldStride = *
I;
2565 const SCEV *NewStride = *NewStrideIter;
2576 dyn_cast_or_null<SCEVConstant>(
getExactSDiv(NewStride, OldStride,
2578 if (Factor->getAPInt().getMinSignedBits() <= 64)
2579 Factors.insert(Factor->getAPInt().getSExtValue());
2584 if (Factor->getAPInt().getMinSignedBits() <= 64)
2585 Factors.insert(Factor->getAPInt().getSExtValue());
2591 if (Types.size() == 1)
2603 for(; OI != OE; ++OI) {
2604 if (
Instruction *Oper = dyn_cast<Instruction>(*OI)) {
2609 dyn_cast<SCEVAddRecExpr>(SE.
getSCEV(Oper))) {
2621 if (
TruncInst *Trunc = dyn_cast<TruncInst>(Oper))
2622 return Trunc->getOperand(0);
2655 return getExprBase(cast<SCEVTruncateExpr>(S)->getOperand());
2657 return getExprBase(cast<SCEVZeroExtendExpr>(S)->getOperand());
2659 return getExprBase(cast<SCEVSignExtendExpr>(S)->getOperand());
2665 for (std::reverse_iterator<SCEVAddExpr::op_iterator>
I(Add->
op_end()),
2667 const SCEV *SubExpr = *
I;
2677 return getExprBase(cast<SCEVAddRecExpr>(S)->getStart());
2686 bool IVChain::isProfitableIncrement(
const SCEV *OperExpr,
2687 const SCEV *IncExpr,
2695 if (!isa<SCEVConstant>(IncExpr)) {
2697 if (isa<SCEVConstant>(SE.
getMinusSCEV(OperExpr, HeadExpr)))
2721 if (!Chain.hasIncs())
2724 if (!Users.
empty()) {
2725 DEBUG(
dbgs() <<
"Chain: " << *Chain.Incs[0].UserInst <<
" users:\n";
2727 dbgs() <<
" " << *Inst <<
"\n";
2731 assert(!Chain.Incs.empty() &&
"empty IV chains are not allowed");
2739 if (isa<PHINode>(Chain.tailUserInst())
2740 && SE.
getSCEV(Chain.tailUserInst()) == Chain.Incs[0].IncExpr) {
2743 const SCEV *LastIncExpr =
nullptr;
2744 unsigned NumConstIncrements = 0;
2745 unsigned NumVarIncrements = 0;
2746 unsigned NumReusedIncrements = 0;
2747 for (
const IVInc &Inc : Chain) {
2748 if (Inc.IncExpr->isZero())
2753 if (isa<SCEVConstant>(Inc.IncExpr)) {
2754 ++NumConstIncrements;
2758 if (Inc.IncExpr == LastIncExpr)
2759 ++NumReusedIncrements;
2763 LastIncExpr = Inc.IncExpr;
2768 if (NumConstIncrements > 1)
2775 cost += NumVarIncrements;
2779 cost -= NumReusedIncrements;
2781 DEBUG(
dbgs() <<
"Chain: " << *Chain.Incs[0].UserInst <<
" Cost: " << cost
2798 unsigned ChainIdx = 0, NChains = IVChainVec.size();
2799 const SCEV *LastIncExpr =
nullptr;
2800 for (; ChainIdx < NChains; ++ChainIdx) {
2801 IVChain &Chain = IVChainVec[ChainIdx];
2815 if (isa<PHINode>(UserInst) && isa<PHINode>(Chain.tailUserInst()))
2824 if (Chain.isProfitableIncrement(OperExpr, IncExpr, SE)) {
2825 LastIncExpr = IncExpr;
2831 if (ChainIdx == NChains) {
2832 if (isa<PHINode>(UserInst))
2838 LastIncExpr = OperExpr;
2842 if (!isa<SCEVAddRecExpr>(LastIncExpr))
2845 IVChainVec.push_back(IVChain(IVInc(UserInst, IVOper, LastIncExpr),
2847 ChainUsersVec.
resize(NChains);
2848 DEBUG(
dbgs() <<
"IV Chain#" << ChainIdx <<
" Head: (" << *UserInst
2849 <<
") IV=" << *LastIncExpr <<
"\n");
2851 DEBUG(
dbgs() <<
"IV Chain#" << ChainIdx <<
" Inc: (" << *UserInst
2852 <<
") IV+" << *LastIncExpr <<
"\n");
2854 IVChainVec[ChainIdx].add(IVInc(UserInst, IVOper, LastIncExpr));
2856 IVChain &Chain = IVChainVec[ChainIdx];
2860 if (!LastIncExpr->
isZero()) {
2861 ChainUsersVec[ChainIdx].FarUsers.
insert(NearUsers.
begin(),
2877 IVChain::const_iterator IncIter = Chain.Incs.begin();
2878 IVChain::const_iterator IncEnd = Chain.Incs.end();
2879 for( ; IncIter != IncEnd; ++IncIter) {
2880 if (IncIter->UserInst == OtherUse)
2883 if (IncIter != IncEnd)
2887 && !isa<SCEVUnknown>(SE.
getSCEV(OtherUse))
2888 && IU.isIVUserOrOperand(OtherUse)) {
2891 NearUsers.
insert(OtherUse);
2896 ChainUsersVec[ChainIdx].FarUsers.
erase(UserInst);
2921 void LSRInstance::CollectChains() {
2922 DEBUG(
dbgs() <<
"Collecting IV Chains.\n");
2928 Rung->getBlock() != LoopHeader; Rung = Rung->getIDom()) {
2937 if (isa<PHINode>(I) || !IU.isIVUserOrOperand(&I))
2947 for (
unsigned ChainIdx = 0, NChains = IVChainVec.size();
2948 ChainIdx < NChains; ++ChainIdx) {
2949 ChainUsersVec[ChainIdx].NearUsers.
erase(&I);
2955 while (IVOpIter != IVOpEnd) {
2956 Instruction *IVOpInst = cast<Instruction>(*IVOpIter);
2957 if (UniqueOperands.
insert(IVOpInst).second)
2958 ChainInstruction(&I, IVOpInst, ChainUsersVec);
2959 IVOpIter =
findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
2972 ChainInstruction(PN, IncV, ChainUsersVec);
2975 unsigned ChainIdx = 0;
2976 for (
unsigned UsersIdx = 0, NChains = IVChainVec.size();
2977 UsersIdx < NChains; ++UsersIdx) {
2979 ChainUsersVec[UsersIdx].FarUsers, SE, TTI))
2982 if (ChainIdx != UsersIdx)
2983 IVChainVec[ChainIdx] = IVChainVec[UsersIdx];
2984 FinalizeChain(IVChainVec[ChainIdx]);
2987 IVChainVec.resize(ChainIdx);
2990 void LSRInstance::FinalizeChain(IVChain &Chain) {
2991 assert(!Chain.Incs.empty() &&
"empty IV chains are not allowed");
2992 DEBUG(
dbgs() <<
"Final Chain: " << *Chain.Incs[0].UserInst <<
"\n");
2994 for (
const IVInc &Inc : Chain) {
2995 DEBUG(
dbgs() <<
" Inc: " << *Inc.UserInst <<
"\n");
2996 auto UseI =
find(Inc.UserInst->operands(), Inc.IVOperand);
2997 assert(UseI != Inc.UserInst->op_end() &&
"cannot find IV operand");
2998 IVIncSet.insert(UseI);
3027 const IVInc &Head = Chain.Incs[0];
3032 Value *IVSrc =
nullptr;
3033 while (IVOpIter != IVOpEnd) {
3044 if (SE.
getSCEV(*IVOpIter) == Head.IncExpr
3045 || SE.
getSCEV(IVSrc) == Head.IncExpr) {
3048 IVOpIter =
findIVOperand(std::next(IVOpIter), IVOpEnd, L, SE);
3050 if (IVOpIter == IVOpEnd) {
3052 DEBUG(
dbgs() <<
"Concealed chain head: " << *Head.UserInst <<
"\n");
3056 DEBUG(
dbgs() <<
"Generate chain at: " << *IVSrc <<
"\n");
3057 Type *IVTy = IVSrc->getType();
3059 const SCEV *LeftOverExpr =
nullptr;
3060 for (
const IVInc &Inc : Chain) {
3062 if (isa<PHINode>(InsertPt))
3063 InsertPt = L->getLoopLatch()->getTerminator();
3067 Value *IVOper = IVSrc;
3068 if (!Inc.IncExpr->isZero()) {
3072 LeftOverExpr = LeftOverExpr ?
3073 SE.
getAddExpr(LeftOverExpr, IncExpr) : IncExpr;
3075 if (LeftOverExpr && !LeftOverExpr->
isZero()) {
3081 IVOper = Rewriter.
expandCodeFor(IVOperExpr, IVTy, InsertPt);
3085 assert(IVTy == IVOper->
getType() &&
"inconsistent IV increment type");
3087 LeftOverExpr =
nullptr;
3090 Type *OperTy = Inc.IVOperand->getType();
3091 if (IVTy != OperTy) {
3093 "cannot extend a chained IV");
3095 IVOper = Builder.CreateTruncOrBitCast(IVOper, OperTy,
"lsr.chain");
3097 Inc.UserInst->replaceUsesOfWith(Inc.IVOperand, IVOper);
3102 if (isa<PHINode>(Chain.tailUserInst())) {
3111 Value *IVOper = IVSrc;
3113 if (IVTy != PostIncTy) {
3115 IRBuilder<> Builder(L->getLoopLatch()->getTerminator());
3117 IVOper = Builder.CreatePointerCast(IVSrc, PostIncTy,
"lsr.chain");
3125 void LSRInstance::CollectFixupsAndInitialFormulae() {
3130 find(UserInst->
operands(), U.getOperandValToReplace());
3131 assert(UseI != UserInst->
op_end() &&
"cannot find IV operand");
3132 if (IVIncSet.count(UseI)) {
3133 DEBUG(
dbgs() <<
"Use is in profitable chain: " << **UseI <<
'\n');
3138 MemAccessTy AccessTy;
3139 if (
isAddressUse(UserInst, U.getOperandValToReplace())) {
3144 const SCEV *S = IU.getExpr(U);
3153 if (
ICmpInst *CI = dyn_cast<ICmpInst>(UserInst))
3154 if (CI->isEquality()) {
3157 Value *
NV = CI->getOperand(1);
3158 if (NV == U.getOperandValToReplace()) {
3159 CI->setOperand(1, CI->getOperand(0));
3160 CI->setOperand(0, NV);
3161 NV = CI->getOperand(1);
3171 Kind = LSRUse::ICmpZero;
3177 for (
size_t i = 0, e = Factors.size(); i != e; ++i)
3178 if (Factors[i] != -1)
3179 Factors.insert(-(uint64_t)Factors[i]);
3184 std::pair<size_t, int64_t> P = getUse(S, Kind, AccessTy);
3185 size_t LUIdx = P.first;
3186 int64_t Offset = P.second;
3187 LSRUse &LU = Uses[LUIdx];
3190 LSRFixup &LF = LU.getNewFixup();
3191 LF.UserInst = UserInst;
3192 LF.OperandValToReplace = U.getOperandValToReplace();
3193 LF.PostIncLoops = TmpPostIncLoops;
3195 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3197 if (!LU.WidestFixupType ||
3200 LU.WidestFixupType = LF.OperandValToReplace->getType();
3203 if (LU.Formulae.empty()) {
3204 InsertInitialFormula(S, LU, LUIdx);
3205 CountRegisters(LU.Formulae.back(), LUIdx);
3215 LSRInstance::InsertInitialFormula(
const SCEV *S, LSRUse &LU,
size_t LUIdx) {
3218 LU.RigidFormula =
true;
3221 F.initialMatch(S, L, SE);
3222 bool Inserted = InsertFormula(LU, LUIdx, F);
3223 assert(Inserted &&
"Initial formula already exists!"); (void)Inserted;
3229 LSRInstance::InsertSupplementalFormula(
const SCEV *S,
3230 LSRUse &LU,
size_t LUIdx) {
3232 F.BaseRegs.push_back(S);
3233 F.HasBaseReg =
true;
3234 bool Inserted = InsertFormula(LU, LUIdx, F);
3235 assert(Inserted &&
"Supplemental formula already exists!"); (void)Inserted;
3239 void LSRInstance::CountRegisters(
const Formula &F,
size_t LUIdx) {
3241 RegUses.countRegister(F.ScaledReg, LUIdx);
3242 for (
const SCEV *BaseReg : F.BaseRegs)
3243 RegUses.countRegister(BaseReg, LUIdx);
3248 bool LSRInstance::InsertFormula(LSRUse &LU,
unsigned LUIdx,
const Formula &F) {
3250 assert(
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F) &&
3251 "Formula is illegal");
3253 if (!LU.InsertFormula(F, *L))
3256 CountRegisters(F, LUIdx);
3266 LSRInstance::CollectLoopInvariantFixupsAndFormulae() {
3270 while (!Worklist.
empty()) {
3274 if (!Visited.
insert(S).second)
3278 Worklist.
append(N->op_begin(), N->op_end());
3279 else if (
const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
3281 else if (
const SCEVUDivExpr *
D = dyn_cast<SCEVUDivExpr>(S)) {
3284 }
else if (
const SCEVUnknown *US = dyn_cast<SCEVUnknown>(S)) {
3285 const Value *V = US->getValue();
3286 if (
const Instruction *Inst = dyn_cast<Instruction>(V)) {
3288 if (L->contains(Inst))
continue;
3289 }
else if (isa<UndefValue>(V))
3292 for (
const Use &U : V->
uses()) {
3302 const BasicBlock *UseBB = !isa<PHINode>(UserInst) ?
3304 cast<PHINode>(UserInst)->getIncomingBlock(
3305 PHINode::getIncomingValueNumForOperand(U.getOperandNo()));
3306 if (!DT.
dominates(L->getHeader(), UseBB))
3317 const SCEV *UserS = SE.
getSCEV(const_cast<Instruction *>(UserInst));
3319 if (!isa<SCEVUnknown>(UserS))
3323 SE.
getUnknown(const_cast<Instruction *>(UserInst)));
3328 if (
const ICmpInst *ICI = dyn_cast<ICmpInst>(UserInst)) {
3329 unsigned OtherIdx = !U.getOperandNo();
3330 Value *OtherOp =
const_cast<Value *
>(ICI->getOperand(OtherIdx));
3335 std::pair<size_t, int64_t> P = getUse(
3337 size_t LUIdx = P.first;
3338 int64_t Offset = P.second;
3339 LSRUse &LU = Uses[LUIdx];
3340 LSRFixup &LF = LU.getNewFixup();
3341 LF.UserInst =
const_cast<Instruction *
>(UserInst);
3342 LF.OperandValToReplace = U;
3344 LU.AllFixupsOutsideLoop &= LF.isUseFullyOutsideLoop(L);
3345 if (!LU.WidestFixupType ||
3348 LU.WidestFixupType = LF.OperandValToReplace->getType();
3349 InsertSupplementalFormula(US, LU, LUIdx);
3350 CountRegisters(LU.Formulae.back(), Uses.size() - 1);
3366 unsigned Depth = 0) {
3373 for (
const SCEV *S :
Add->operands()) {
3379 }
else if (
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S)) {
3388 if (Remainder && (AR->
getLoop() == L || !isa<SCEVAddRecExpr>(Remainder))) {
3389 Ops.push_back(C ? SE.getMulExpr(C, Remainder) : Remainder);
3390 Remainder =
nullptr;
3394 Remainder = SE.getConstant(AR->
getType(), 0);
3395 return SE.getAddRecExpr(Remainder,
3401 }
else if (
const SCEVMulExpr *Mul = dyn_cast<SCEVMulExpr>(S)) {
3403 if (Mul->getNumOperands() != 2)
3406 dyn_cast<SCEVConstant>(Mul->getOperand(0))) {
3407 C = C ? cast<SCEVConstant>(SE.
getMulExpr(C, Op0)) : Op0;
3408 const SCEV *Remainder =
3411 Ops.push_back(SE.getMulExpr(C, Remainder));
3419 void LSRInstance::GenerateReassociationsImpl(LSRUse &LU,
unsigned LUIdx,
3420 const Formula &
Base,
3421 unsigned Depth,
size_t Idx,
3423 const SCEV *BaseReg = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3429 if (AddOps.
size() == 1)
3444 LU.AccessTy, *J, Base.getNumRegs() > 1))
3450 InnerAddOps.append(std::next(J),
3455 if (InnerAddOps.size() == 1 &&
3457 LU.AccessTy, InnerAddOps[0], Base.getNumRegs() > 1))
3473 F.ScaledReg =
nullptr;
3475 F.BaseRegs.erase(F.BaseRegs.begin() + Idx);
3476 }
else if (IsScaledReg)
3477 F.ScaledReg = InnerSum;
3479 F.BaseRegs[Idx] = InnerSum;
3489 F.BaseRegs.push_back(*J);
3494 if (InsertFormula(LU, LUIdx, F))
3497 GenerateReassociations(LU, LUIdx, LU.Formulae.back(), Depth + 1);
3502 void LSRInstance::GenerateReassociations(LSRUse &LU,
unsigned LUIdx,
3503 Formula Base,
unsigned Depth) {
3504 assert(Base.isCanonical(*L) &&
"Input must be in the canonical form");
3509 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3510 GenerateReassociationsImpl(LU, LUIdx, Base, Depth, i);
3512 if (Base.Scale == 1)
3513 GenerateReassociationsImpl(LU, LUIdx, Base, Depth,
3519 void LSRInstance::GenerateCombinations(LSRUse &LU,
unsigned LUIdx,
3522 if (Base.BaseRegs.size() + (Base.Scale == 1) <= 1)
3531 for (
const SCEV *BaseReg : Base.BaseRegs) {
3536 F.BaseRegs.push_back(BaseReg);
3538 if (Ops.
size() > 1) {
3544 F.BaseRegs.push_back(Sum);
3546 (void)InsertFormula(LU, LUIdx, F);
3552 void LSRInstance::GenerateSymbolicOffsetsImpl(LSRUse &LU,
unsigned LUIdx,
3553 const Formula &Base,
size_t Idx,
3555 const SCEV *
G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3561 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3566 F.BaseRegs[Idx] =
G;
3567 (void)InsertFormula(LU, LUIdx, F);
3571 void LSRInstance::GenerateSymbolicOffsets(LSRUse &LU,
unsigned LUIdx,
3574 if (Base.BaseGV)
return;
3576 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3577 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, i);
3578 if (Base.Scale == 1)
3579 GenerateSymbolicOffsetsImpl(LU, LUIdx, Base, -1,
3584 void LSRInstance::GenerateConstantOffsetsImpl(
3585 LSRUse &LU,
unsigned LUIdx,
const Formula &Base,
3587 const SCEV *G = IsScaledReg ? Base.ScaledReg : Base.BaseRegs[Idx];
3588 for (int64_t Offset : Worklist) {
3590 F.BaseOffset = (uint64_t)Base.BaseOffset - Offset;
3591 if (
isLegalUse(TTI, LU.MinOffset - Offset, LU.MaxOffset - Offset, LU.Kind,
3599 F.ScaledReg =
nullptr;
3601 F.deleteBaseReg(F.BaseRegs[Idx]);
3603 }
else if (IsScaledReg)
3606 F.BaseRegs[Idx] = NewG;
3608 (void)InsertFormula(LU, LUIdx, F);
3613 if (G->
isZero() || Imm == 0)
3616 F.BaseOffset = (uint64_t)F.BaseOffset + Imm;
3617 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy, F))
3622 F.BaseRegs[Idx] =
G;
3623 (void)InsertFormula(LU, LUIdx, F);
3627 void LSRInstance::GenerateConstantOffsets(LSRUse &LU,
unsigned LUIdx,
3633 if (LU.MaxOffset != LU.MinOffset)
3636 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i)
3637 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, i);
3638 if (Base.Scale == 1)
3639 GenerateConstantOffsetsImpl(LU, LUIdx, Base, Worklist, -1,
3645 void LSRInstance::GenerateICmpZeroScales(LSRUse &LU,
unsigned LUIdx,
3647 if (LU.Kind != LSRUse::ICmpZero)
return;
3650 Type *IntTy = Base.getType();
3655 if (LU.MinOffset != LU.MaxOffset)
return;
3657 assert(!Base.BaseGV &&
"ICmpZero use is not legal!");
3660 for (int64_t Factor : Factors) {
3662 if (Base.BaseOffset == INT64_MIN && Factor == -1)
3664 int64_t NewBaseOffset = (uint64_t)Base.BaseOffset * Factor;
3665 if (NewBaseOffset / Factor != Base.BaseOffset)
3669 !ConstantInt::isValueValidForType(IntTy, NewBaseOffset))
3673 int64_t Offset = LU.MinOffset;
3674 if (Offset == INT64_MIN && Factor == -1)
3676 Offset = (uint64_t)Offset * Factor;
3677 if (Offset / Factor != LU.MinOffset)
3681 !ConstantInt::isValueValidForType(IntTy, Offset))
3685 F.BaseOffset = NewBaseOffset;
3688 if (!
isLegalUse(TTI, Offset, Offset, LU.Kind, LU.AccessTy, F))
3692 F.BaseOffset = (uint64_t)F.BaseOffset + Offset - LU.MinOffset;
3697 for (
size_t i = 0, e = F.BaseRegs.size(); i != e; ++i) {
3698 F.BaseRegs[i] = SE.
getMulExpr(F.BaseRegs[i], FactorS);
3699 if (
getExactSDiv(F.BaseRegs[i], FactorS, SE) != Base.BaseRegs[i])
3705 F.ScaledReg = SE.
getMulExpr(F.ScaledReg, FactorS);
3706 if (
getExactSDiv(F.ScaledReg, FactorS, SE) != Base.ScaledReg)
3711 if (F.UnfoldedOffset != 0) {
3712 if (F.UnfoldedOffset == INT64_MIN && Factor == -1)
3714 F.UnfoldedOffset = (uint64_t)F.UnfoldedOffset * Factor;
3715 if (F.UnfoldedOffset / Factor != Base.UnfoldedOffset)
3719 !ConstantInt::isValueValidForType(IntTy, F.UnfoldedOffset))
3724 (void)InsertFormula(LU, LUIdx, F);
3731 void LSRInstance::GenerateScales(LSRUse &LU,
unsigned LUIdx, Formula Base) {
3733 Type *IntTy = Base.getType();
3738 if (Base.Scale != 0 && !Base.unscale())
3741 assert(Base.Scale == 0 &&
"unscale did not did its job!");
3744 for (int64_t Factor : Factors) {
3745 Base.Scale = Factor;
3746 Base.HasBaseReg = Base.BaseRegs.size() > 1;
3748 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3753 isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LSRUse::Special,
3754 LU.AccessTy, Base) &&
3755 LU.AllFixupsOutsideLoop)
3756 LU.Kind = LSRUse::Special;
3762 if (LU.Kind == LSRUse::ICmpZero &&
3763 !Base.HasBaseReg && Base.BaseOffset == 0 && !Base.BaseGV)
3766 for (
size_t i = 0, e = Base.BaseRegs.size(); i != e; ++i) {
3768 if (AR && (AR->
getLoop() == L || LU.AllFixupsOutsideLoop)) {
3777 F.ScaledReg = Quotient;
3778 F.deleteBaseReg(F.BaseRegs[i]);
3782 if (F.Scale == 1 && (F.BaseRegs.empty() ||
3783 (AR->
getLoop() != L && LU.AllFixupsOutsideLoop)))
3787 if (F.Scale == 1 && LU.AllFixupsOutsideLoop)
3789 (void)InsertFormula(LU, LUIdx, F);
3797 void LSRInstance::GenerateTruncates(LSRUse &LU,
unsigned LUIdx, Formula Base) {
3799 if (Base.BaseGV)
return;
3802 Type *DstTy = Base.getType();
3806 for (
Type *SrcTy : Types) {
3811 for (
const SCEV *&BaseReg : F.BaseRegs)
3816 if (!F.hasRegsUsedByUsesOtherThan(LUIdx, RegUses))
3820 (void)InsertFormula(LU, LUIdx, F);
3833 const SCEV *OrigReg;
3835 WorkItem(
size_t LI, int64_t I,
const SCEV *R)
3836 : LUIdx(LI), Imm(I), OrigReg(R) {}
3845 OS <<
"in formulae referencing " << *OrigReg <<
" in use " << LUIdx
3846 <<
" , add offset " << Imm;
3849 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
3857 void LSRInstance::GenerateCrossUseConstantOffsets() {
3859 typedef std::map<int64_t, const SCEV *> ImmMapTy;
3863 for (
const SCEV *
Use : RegUses) {
3866 auto Pair = Map.
insert(std::make_pair(Reg, ImmMapTy()));
3869 Pair.first->second.insert(std::make_pair(Imm,
Use));
3870 UsedByIndicesMap[
Reg] |= RegUses.getUsedByIndices(
Use);
3878 for (
const SCEV *Reg : Sequence) {
3879 const ImmMapTy &Imms = Map.
find(Reg)->second;
3882 if (Imms.size() == 1)
3885 DEBUG(
dbgs() <<
"Generating cross-use offsets for " << *Reg <<
':';
3886 for (
const auto &Entry : Imms)
3887 dbgs() <<
' ' << Entry.first;
3891 for (ImmMapTy::const_iterator J = Imms.begin(), JE = Imms.end();
3893 const SCEV *OrigReg = J->second;
3895 int64_t JImm = J->first;
3896 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(OrigReg);
3898 if (!isa<SCEVConstant>(OrigReg) &&
3899 UsedByIndicesMap[Reg].
count() == 1) {
3900 DEBUG(
dbgs() <<
"Skipping cross-use reuse for " << *OrigReg <<
'\n');
3906 ImmMapTy::const_iterator OtherImms[] = {
3907 Imms.begin(), std::prev(Imms.end()),
3908 Imms.lower_bound((Imms.begin()->first + std::prev(Imms.end())->
first) /
3912 ImmMapTy::const_iterator M = OtherImms[i];
3913 if (M == J || M == JE)
continue;
3916 int64_t Imm = (uint64_t)JImm - M->first;
3919 if (UniqueItems.
insert(std::make_pair(LUIdx, Imm)).second)
3920 WorkItems.
push_back(WorkItem(LUIdx, Imm, OrigReg));
3927 UsedByIndicesMap.
clear();
3928 UniqueItems.
clear();
3931 for (
const WorkItem &WI : WorkItems) {
3932 size_t LUIdx = WI.LUIdx;
3933 LSRUse &LU = Uses[LUIdx];
3934 int64_t Imm = WI.Imm;
3935 const SCEV *OrigReg = WI.OrigReg;
3938 const SCEV *NegImmS = SE.
getSCEV(ConstantInt::get(IntTy, -(uint64_t)Imm));
3942 for (
size_t L = 0,
LE = LU.Formulae.size(); L !=
LE; ++
L) {
3943 Formula F = LU.Formulae[
L];
3950 if (F.ScaledReg == OrigReg) {
3951 int64_t Offset = (uint64_t)F.BaseOffset + Imm * (uint64_t)F.Scale;
3953 if (F.referencesReg(SE.
getSCEV(
3954 ConstantInt::get(IntTy, -(uint64_t)Offset))))
3957 NewF.BaseOffset =
Offset;
3958 if (!
isLegalUse(TTI, LU.MinOffset, LU.MaxOffset, LU.Kind, LU.AccessTy,
3961 NewF.ScaledReg = SE.
getAddExpr(NegImmS, NewF.ScaledReg);
3966 if (
const SCEVConstant *C = dyn_cast<SCEVConstant>(NewF.ScaledReg))
3968 (C->getAPInt().abs() *
APInt(BitWidth, F.Scale))
3973 NewF.canonicalize(*this->L);
3974 (void)InsertFormula(LU, LUIdx, NewF);
3977 for (
size_t N = 0,
NE = F.BaseRegs.size(); N !=
NE; ++
N) {
3978 const SCEV *BaseReg = F.BaseRegs[
N];
3979 if (BaseReg != OrigReg)
3982 NewF.BaseOffset = (uint64_t)NewF.BaseOffset + Imm;
3984 LU.Kind, LU.AccessTy, NewF)) {
3988 NewF.UnfoldedOffset = (uint64_t)NewF.UnfoldedOffset + Imm;
3990 NewF.BaseRegs[
N] = SE.
getAddExpr(NegImmS, BaseReg);
3995 for (
const SCEV *NewReg : NewF.BaseRegs)
3996 if (
const SCEVConstant *C = dyn_cast<SCEVConstant>(NewReg))
3997 if ((C->getAPInt() + NewF.BaseOffset)
4001 countTrailingZeros<uint64_t>(NewF.BaseOffset))
4005 NewF.canonicalize(*this->L);
4006 (void)InsertFormula(LU, LUIdx, NewF);
4017 LSRInstance::GenerateAllReuseFormulae() {
4020 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4021 LSRUse &LU = Uses[LUIdx];
4022 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4023 GenerateReassociations(LU, LUIdx, LU.Formulae[i]);
4024 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4025 GenerateCombinations(LU, LUIdx, LU.Formulae[i]);
4027 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4028 LSRUse &LU = Uses[LUIdx];
4029 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4030 GenerateSymbolicOffsets(LU, LUIdx, LU.Formulae[i]);
4031 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4032 GenerateConstantOffsets(LU, LUIdx, LU.Formulae[i]);
4033 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4034 GenerateICmpZeroScales(LU, LUIdx, LU.Formulae[i]);
4035 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4036 GenerateScales(LU, LUIdx, LU.Formulae[i]);
4038 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4039 LSRUse &LU = Uses[LUIdx];
4040 for (
size_t i = 0, f = LU.Formulae.size(); i != f; ++i)
4041 GenerateTruncates(LU, LUIdx, LU.Formulae[i]);
4044 GenerateCrossUseConstantOffsets();
4047 "After generating reuse formulae:\n";
4048 print_uses(
dbgs()));
4053 void LSRInstance::FilterOutUndesirableDedicatedRegisters() {
4058 bool ChangedFormulae =
false;
4065 BestFormulaeTy BestFormulae;
4067 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4068 LSRUse &LU = Uses[LUIdx];
4072 for (
size_t FIdx = 0, NumForms = LU.Formulae.size();
4073 FIdx != NumForms; ++FIdx) {
4074 Formula &F = LU.Formulae[FIdx];
4085 CostF.RateFormula(TTI, F, Regs, VisitedRegs, L, SE, DT, LU, &LoserRegs);
4086 if (CostF.isLoser()) {
4098 for (
const SCEV *Reg : F.BaseRegs) {
4099 if (RegUses.isRegUsedByUsesOtherThan(Reg, LUIdx))
4103 RegUses.isRegUsedByUsesOtherThan(F.ScaledReg, LUIdx))
4109 std::pair<BestFormulaeTy::const_iterator, bool> P =
4110 BestFormulae.insert(std::make_pair(Key, FIdx));
4114 Formula &Best = LU.Formulae[P.first->second];
4118 CostBest.RateFormula(TTI, Best, Regs, VisitedRegs, L, SE, DT, LU);
4119 if (CostF.isLess(CostBest, TTI))
4123 " in favor of formula "; Best.print(
dbgs());
4127 ChangedFormulae =
true;
4129 LU.DeleteFormula(F);
4137 LU.RecomputeRegs(LUIdx, RegUses);
4140 BestFormulae.clear();
4143 DEBUG(
if (ChangedFormulae) {
4145 "After filtering out undesirable candidates:\n";
4156 size_t LSRInstance::EstimateSearchSpaceComplexity()
const {
4158 for (
const LSRUse &LU : Uses) {
4159 size_t FSize = LU.Formulae.size();
4160 if (FSize >= ComplexityLimit) {
4165 if (Power >= ComplexityLimit)
4174 void LSRInstance::NarrowSearchSpaceByDetectingSupersets() {
4175 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4176 DEBUG(
dbgs() <<
"The search space is too complex.\n");
4178 DEBUG(
dbgs() <<
"Narrowing the search space by eliminating formulae "
4179 "which use a superset of registers used by other "
4182 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4183 LSRUse &LU = Uses[LUIdx];
4185 for (
size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4186 Formula &F = LU.Formulae[i];
4191 I = F.BaseRegs.begin(),
E = F.BaseRegs.end(); I !=
E; ++
I) {
4192 if (
const SCEVConstant *C = dyn_cast<SCEVConstant>(*I)) {
4195 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4196 (I - F.BaseRegs.begin()));
4197 if (LU.HasFormulaWithSameRegs(NewF)) {
4199 LU.DeleteFormula(F);
4205 }
else if (
const SCEVUnknown *U = dyn_cast<SCEVUnknown>(*I)) {
4206 if (
GlobalValue *GV = dyn_cast<GlobalValue>(U->getValue()))
4210 NewF.BaseRegs.erase(NewF.BaseRegs.begin() +
4211 (I - F.BaseRegs.begin()));
4212 if (LU.HasFormulaWithSameRegs(NewF)) {
4215 LU.DeleteFormula(F);
4226 LU.RecomputeRegs(LUIdx, RegUses);
4229 DEBUG(
dbgs() <<
"After pre-selection:\n";
4230 print_uses(
dbgs()));
4236 void LSRInstance::NarrowSearchSpaceByCollapsingUnrolledCode() {
4237 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4240 DEBUG(
dbgs() <<
"The search space is too complex.\n"
4241 "Narrowing the search space by assuming that uses separated "
4242 "by a constant offset will use the same registers.\n");
4246 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4247 LSRUse &LU = Uses[LUIdx];
4248 for (
const Formula &F : LU.Formulae) {
4249 if (F.BaseOffset == 0 || (F.Scale != 0 && F.Scale != 1))
4252 LSRUse *LUThatHas = FindUseWithSimilarFormula(F, LU);
4256 if (!reconcileNewOffset(*LUThatHas, F.BaseOffset,
false,
4257 LU.Kind, LU.AccessTy))
4262 LUThatHas->AllFixupsOutsideLoop &= LU.AllFixupsOutsideLoop;
4265 for (LSRFixup &Fixup : LU.Fixups) {
4266 Fixup.Offset += F.BaseOffset;
4267 LUThatHas->pushFixup(Fixup);
4268 DEBUG(
dbgs() <<
"New fixup has offset " << Fixup.Offset <<
'\n');
4273 for (
size_t i = 0, e = LUThatHas->Formulae.size(); i != e; ++i) {
4274 Formula &F = LUThatHas->Formulae[i];
4275 if (!
isLegalUse(TTI, LUThatHas->MinOffset, LUThatHas->MaxOffset,
4276 LUThatHas->Kind, LUThatHas->AccessTy, F)) {
4279 LUThatHas->DeleteFormula(F);
4287 LUThatHas->RecomputeRegs(LUThatHas - &Uses.front(), RegUses);
4290 DeleteUse(LU, LUIdx);
4297 DEBUG(
dbgs() <<
"After pre-selection:\n"; print_uses(
dbgs()));
4303 void LSRInstance::NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters(){
4304 if (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4305 DEBUG(
dbgs() <<
"The search space is too complex.\n");
4307 DEBUG(
dbgs() <<
"Narrowing the search space by re-filtering out "
4308 "undesirable dedicated registers.\n");
4310 FilterOutUndesirableDedicatedRegisters();
4312 DEBUG(
dbgs() <<
"After pre-selection:\n";
4313 print_uses(
dbgs()));
4326 void LSRInstance::NarrowSearchSpaceByFilterFormulaWithSameScaledReg() {
4327 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4330 DEBUG(
dbgs() <<
"The search space is too complex.\n"
4331 "Narrowing the search space by choosing the best Formula "
4332 "from the Formulae with the same Scale and ScaledReg.\n");
4336 BestFormulaeTy BestFormulae;
4338 bool ChangedFormulae =
false;
4343 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4344 LSRUse &LU = Uses[LUIdx];
4348 auto IsBetterThan = [&](Formula &FA, Formula &FB) {
4353 size_t FARegNum = 0;
4354 for (
const SCEV *Reg : FA.BaseRegs) {
4355 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4356 FARegNum += (NumUses - UsedByIndices.
count() + 1);
4358 size_t FBRegNum = 0;
4359 for (
const SCEV *Reg : FB.BaseRegs) {
4360 const SmallBitVector &UsedByIndices = RegUses.getUsedByIndices(Reg);
4361 FBRegNum += (NumUses - UsedByIndices.
count() + 1);
4363 if (FARegNum != FBRegNum)
4364 return FARegNum < FBRegNum;
4368 Cost CostFA, CostFB;
4370 CostFA.RateFormula(TTI, FA, Regs, VisitedRegs, L, SE, DT, LU);
4372 CostFB.RateFormula(TTI, FB, Regs, VisitedRegs, L, SE, DT, LU);
4373 return CostFA.isLess(CostFB, TTI);
4377 for (
size_t FIdx = 0, NumForms = LU.Formulae.size(); FIdx != NumForms;
4379 Formula &F = LU.Formulae[FIdx];
4382 auto P = BestFormulae.insert({{F.ScaledReg, F.Scale}, FIdx});
4386 Formula &Best = LU.Formulae[P.first->second];
4387 if (IsBetterThan(F, Best))
4391 " in favor of formula ";
4392 Best.print(
dbgs());
dbgs() <<
'\n');
4394 ChangedFormulae =
true;
4396 LU.DeleteFormula(F);
4402 LU.RecomputeRegs(LUIdx, RegUses);
4405 BestFormulae.clear();
4408 DEBUG(
if (ChangedFormulae) {
4410 "After filtering out undesirable candidates:\n";
4458 void LSRInstance::NarrowSearchSpaceByDeletingCostlyFormulas() {
4459 if (EstimateSearchSpaceComplexity() < ComplexityLimit)
4468 DEBUG(
dbgs() <<
"The search space is too complex.\n");
4472 for (
const SCEV *Reg : RegUses) {
4473 if (UniqRegs.
count(Reg))
4476 for (
const LSRUse &LU : Uses) {
4477 if (!LU.Regs.count(Reg))
4479 float P = LU.getNotSelectedProbability(Reg);
4485 RegNumMap.
insert(std::make_pair(Reg, PNotSel));
4488 DEBUG(
dbgs() <<
"Narrowing the search space by deleting costly formulas\n");
4491 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4492 LSRUse &LU = Uses[LUIdx];
4494 if (LU.Formulae.size() < 2)
4499 float FMinRegNum = LU.Formulae[0].getNumRegs();
4500 float FMinARegNum = LU.Formulae[0].getNumRegs();
4502 for (
size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4503 Formula &F = LU.Formulae[i];
4506 for (
const SCEV *BaseReg : F.BaseRegs) {
4507 if (UniqRegs.
count(BaseReg))
4509 FRegNum += RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4510 if (isa<SCEVAddRecExpr>(BaseReg))
4512 RegNumMap[BaseReg] / LU.getNotSelectedProbability(BaseReg);
4514 if (
const SCEV *ScaledReg = F.ScaledReg) {
4515 if (!UniqRegs.
count(ScaledReg)) {
4517 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4518 if (isa<SCEVAddRecExpr>(ScaledReg))
4520 RegNumMap[ScaledReg] / LU.getNotSelectedProbability(ScaledReg);
4523 if (FMinRegNum > FRegNum ||
4524 (FMinRegNum == FRegNum && FMinARegNum > FARegNum)) {
4525 FMinRegNum = FRegNum;
4526 FMinARegNum = FARegNum;
4530 DEBUG(
dbgs() <<
" The formula "; LU.Formulae[MinIdx].print(
dbgs());
4531 dbgs() <<
" with min reg num " << FMinRegNum <<
'\n');
4533 std::swap(LU.Formulae[MinIdx], LU.Formulae[0]);
4534 while (LU.Formulae.size() != 1) {
4535 DEBUG(
dbgs() <<
" Deleting "; LU.Formulae.back().print(
dbgs());
4537 LU.Formulae.pop_back();
4539 LU.RecomputeRegs(LUIdx, RegUses);
4540 assert(LU.Formulae.size() == 1 &&
"Should be exactly 1 min regs formula");
4541 Formula &F = LU.Formulae[0];
4544 UniqRegs.
insert(F.BaseRegs.begin(), F.BaseRegs.end());
4546 UniqRegs.
insert(F.ScaledReg);
4548 DEBUG(
dbgs() <<
"After pre-selection:\n";
4549 print_uses(
dbgs()));
4556 void LSRInstance::NarrowSearchSpaceByPickingWinnerRegs() {
4560 while (EstimateSearchSpaceComplexity() >= ComplexityLimit) {
4563 DEBUG(
dbgs() <<
"The search space is too complex.\n");
4567 const SCEV *Best =
nullptr;
4568 unsigned BestNum = 0;
4569 for (
const SCEV *Reg : RegUses) {
4570 if (Taken.
count(Reg))
4574 BestNum = RegUses.getUsedByIndices(Reg).count();
4576 unsigned Count = RegUses.getUsedByIndices(Reg).count();
4577 if (Count > BestNum) {
4584 DEBUG(
dbgs() <<
"Narrowing the search space by assuming " << *Best
4585 <<
" will yield profitable reuse.\n");
4590 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx) {
4591 LSRUse &LU = Uses[LUIdx];
4592 if (!LU.Regs.count(Best))
continue;
4595 for (
size_t i = 0, e = LU.Formulae.size(); i != e; ++i) {
4596 Formula &F = LU.Formulae[i];
4597 if (!F.referencesReg(Best)) {
4599 LU.DeleteFormula(F);
4603 assert(e != 0 &&
"Use has no formulae left! Is Regs inconsistent?");
4609 LU.RecomputeRegs(LUIdx, RegUses);
4612 DEBUG(
dbgs() <<
"After pre-selection:\n";
4613 print_uses(
dbgs()));
4621 void LSRInstance::NarrowSearchSpaceUsingHeuristics() {
4622 NarrowSearchSpaceByDetectingSupersets();
4623 NarrowSearchSpaceByCollapsingUnrolledCode();
4624 NarrowSearchSpaceByRefilteringUndesirableDedicatedRegisters();
4626 NarrowSearchSpaceByFilterFormulaWithSameScaledReg();
4628 NarrowSearchSpaceByDeletingCostlyFormulas();
4630 NarrowSearchSpaceByPickingWinnerRegs();
4637 const Cost &CurCost,
4650 const LSRUse &LU = Uses[Workspace.
size()];
4657 for (
const SCEV *S : CurRegs)
4658 if (LU.Regs.count(S))
4663 for (
const Formula &F : LU.Formulae) {
4667 int NumReqRegsToFind =
std::min(F.getNumRegs(), ReqRegs.
size());
4668 for (
const SCEV *Reg : ReqRegs) {
4669 if ((F.ScaledReg && F.ScaledReg == Reg) ||
4672 if (NumReqRegsToFind == 0)
4676 if (NumReqRegsToFind != 0) {
4686 NewCost.RateFormula(TTI, F, NewRegs, VisitedRegs, L, SE, DT, LU);
4687 if (NewCost.isLess(SolutionCost, TTI)) {
4689 if (Workspace.
size() != Uses.size()) {
4690 SolveRecurse(Solution, SolutionCost, Workspace, NewCost,
4691 NewRegs, VisitedRegs);
4692 if (F.getNumRegs() == 1 && Workspace.
size() == 1)
4693 VisitedRegs.
insert(F.ScaledReg ? F.ScaledReg : F.BaseRegs[0]);
4696 dbgs() <<
".\n Regs:";
4697 for (
const SCEV *S : NewRegs)
4698 dbgs() <<
' ' << *S;
4701 SolutionCost = NewCost;
4702 Solution = Workspace;
4714 SolutionCost.Lose();
4718 Workspace.
reserve(Uses.size());
4721 SolveRecurse(Solution, SolutionCost, Workspace, CurCost,
4722 CurRegs, VisitedRegs);
4723 if (Solution.
empty()) {
4724 DEBUG(
dbgs() <<
"\nNo Satisfactory Solution\n");
4730 "The chosen solution requires "; SolutionCost.print(
dbgs());
4732 for (
size_t i = 0, e = Uses.size(); i != e; ++i) {
4734 Uses[i].print(
dbgs());
4737 Solution[i]->print(
dbgs());
4741 assert(Solution.
size() == Uses.size() &&
"Malformed solution!");
4753 bool AllDominate =
true;
4757 if (isa<CatchSwitchInst>(Tentative))
4761 if (Inst == Tentative || !DT.
dominates(Inst, Tentative)) {
4762 AllDominate =
false;
4768 (!BetterPos || !DT.
dominates(Inst, BetterPos)))
4778 const Loop *IPLoop = LI.getLoopFor(IP->getParent());
4779 unsigned IPLoopDepth = IPLoop ? IPLoop->
getLoopDepth() : 0;
4783 if (!Rung)
return IP;
4784 Rung = Rung->getIDom();
4785 if (!Rung)
return IP;
4786 IDom = Rung->getBlock();
4789 const Loop *IDomLoop = LI.getLoopFor(IDom);
4790 unsigned IDomDepth = IDomLoop ? IDomLoop->
getLoopDepth() : 0;
4791 if (IDomDepth <= IPLoopDepth &&
4792 (IDomDepth != IPLoopDepth || IDomLoop == IPLoop))
4813 if (
Instruction *I = dyn_cast<Instruction>(LF.OperandValToReplace))
4815 if (LU.Kind == LSRUse::ICmpZero)
4817 dyn_cast<Instruction>(cast<ICmpInst>(LF.UserInst)->getOperand(1)))
4819 if (LF.PostIncLoops.count(L)) {
4820 if (LF.isUseFullyOutsideLoop(L))
4821 Inputs.
push_back(L->getLoopLatch()->getTerminator());
4827 for (
const Loop *PIL : LF.PostIncLoops) {
4828 if (PIL == L)
continue;
4833 if (!ExitingBlocks.
empty()) {
4835 for (
unsigned i = 1, e = ExitingBlocks.
size(); i != e; ++i)
4841 assert(!isa<PHINode>(LowestIP) && !LowestIP->isEHPad()
4842 && !isa<DbgInfoIntrinsic>(LowestIP) &&
4843 "Insertion point must be a normal instruction");
4850 while (isa<PHINode>(IP)) ++IP;
4853 while (IP->isEHPad()) ++IP;
4856 while (isa<DbgInfoIntrinsic>(IP)) ++IP;
4869 Value *LSRInstance::Expand(
const LSRUse &LU,
const LSRFixup &LF,
4873 if (LU.RigidFormula)
4874 return LF.OperandValToReplace;
4878 IP = AdjustInsertPositionForExpand(IP, LF, LU, Rewriter);
4886 Type *OpTy = LF.OperandValToReplace->getType();
4888 Type *Ty = F.getType();
4902 for (
const SCEV *Reg : F.BaseRegs) {
4903 assert(!Reg->
isZero() &&
"Zero allocated in a base register!");
4911 Value *ICmpScaledV =
nullptr;
4913 const SCEV *ScaledS = F.ScaledReg;
4919 if (LU.Kind == LSRUse::ICmpZero) {
4929 "The only scale supported by ICmpZero uses is -1!");
4972 int64_t Offset = (uint64_t)F.BaseOffset + LF.Offset;
4974 if (LU.Kind == LSRUse::ICmpZero) {
4978 ICmpScaledV = ConstantInt::get(IntTy, -(uint64_t)Offset);
4981 ICmpScaledV = ConstantInt::get(IntTy, Offset);
4991 int64_t UnfoldedOffset = F.UnfoldedOffset;
4992 if (UnfoldedOffset != 0) {
5010 if (LU.Kind == LSRUse::ICmpZero) {
5011 ICmpInst *CI = cast<ICmpInst>(LF.UserInst);
5013 assert(!F.BaseGV &&
"ICmp does not support folding a global value and "
5014 "a scale at the same time!");
5015 if (F.Scale == -1) {
5016 if (ICmpScaledV->
getType() != OpTy) {
5018 CastInst::Create(CastInst::getCastOpcode(ICmpScaledV,
false,
5020 ICmpScaledV, OpTy,
"tmp", CI);
5027 assert((F.Scale == 0 || F.Scale == 1) &&
5028 "ICmp does not support folding a global value and "
5029 "a scale at the same time!");
5033 C = ConstantExpr::getCast(CastInst::getCastOpcode(C,
false,
5047 void LSRInstance::RewriteForPHI(
5048 PHINode *PN,
const LSRUse &LU,
const LSRFixup &LF,
const Formula &F,
5063 Loop *PNLoop = LI.getLoopFor(Parent);
5064 if (!PNLoop || Parent != PNLoop->
getHeader()) {
5070 .setMergeIdenticalEdges()
5071 .setDontDeleteUselessPHIs());
5084 if (L->contains(BB) && !L->contains(PN))
5095 std::pair<DenseMap<BasicBlock *, Value *>::iterator,
bool> Pair =
5096 Inserted.
insert(std::make_pair(BB, static_cast<Value *>(
nullptr)));
5104 Type *OpTy = LF.OperandValToReplace->getType();
5107 CastInst::Create(CastInst::getCastOpcode(FullV,
false,
5109 FullV, LF.OperandValToReplace->getType(),
5113 Pair.first->second = FullV;
5121 void LSRInstance::Rewrite(
const LSRUse &LU,
const LSRFixup &LF,
5126 if (
PHINode *PN = dyn_cast<PHINode>(LF.UserInst)) {
5127 RewriteForPHI(PN, LU, LF, F, Rewriter, DeadInsts);
5130 Expand(LU, LF, F, LF.UserInst->getIterator(),
Rewriter, DeadInsts);
5133 Type *OpTy = LF.OperandValToReplace->getType();
5134 if (FullV->
getType() != OpTy) {
5136 CastInst::Create(CastInst::getCastOpcode(FullV,
false, OpTy,
false),
5137 FullV, OpTy,
"tmp", LF.UserInst);
5146 if (LU.Kind == LSRUse::ICmpZero)
5147 LF.UserInst->setOperand(0, FullV);
5149 LF.UserInst->replaceUsesOfWith(LF.OperandValToReplace, FullV);
5157 void LSRInstance::ImplementSolution(
5173 for (
const IVChain &Chain : IVChainVec) {
5174 if (
PHINode *PN = dyn_cast<PHINode>(Chain.tailUserInst()))
5179 for (
size_t LUIdx = 0, NumUses = Uses.size(); LUIdx != NumUses; ++LUIdx)
5180 for (
const LSRFixup &Fixup : Uses[LUIdx].Fixups) {
5181 Rewrite(Uses[LUIdx], Fixup, *Solution[LUIdx], Rewriter, DeadInsts);
5185 for (
const IVChain &Chain : IVChainVec) {
5186 GenerateIVChain(Chain, Rewriter, DeadInsts);
5199 : IU(IU), SE(SE), DT(DT), LI(LI), TTI(TTI), L(L), Changed(
false),
5200 IVIncInsertPos(nullptr) {
5206 if (IU.
empty())
return;
5210 unsigned NumUsers = 0;
5214 DEBUG(
dbgs() <<
"LSR skipping loop, too many IV Users in " << U <<
"\n");
5220 if (
auto *PN = dyn_cast<PHINode>(U.getUser())) {
5222 if (isa<FuncletPadInst>(FirstNonPHI) ||
5223 isa<CatchSwitchInst>(FirstNonPHI))
5225 if (isa<CatchSwitchInst>(PredBB->getFirstNonPHI()))
5238 Rung; Rung = Rung->getIDom()) {
5241 if (DomLoop && DomLoop->
getHeader() == BB) {
5253 OptimizeLoopTermCond();
5256 if (IU.empty())
return;
5260 DEBUG(
dbgs() <<
"LSR skipping outer loop " << *L <<
"\n");
5266 CollectInterestingTypesAndFactors();
5267 CollectFixupsAndInitialFormulae();
5268 CollectLoopInvariantFixupsAndFormulae();
5270 assert(!Uses.empty() &&
"IVUsers reported at least one use");
5271 DEBUG(
dbgs() <<
"LSR found " << Uses.size() <<
" uses:\n";
5272 print_uses(
dbgs()));
5276 GenerateAllReuseFormulae();
5278 FilterOutUndesirableDedicatedRegisters();
5279 NarrowSearchSpaceUsingHeuristics();
5289 if (Solution.
empty())
5294 for (
const LSRUse &LU : Uses) {
5295 for (
const Formula &F : LU.Formulae)
5297 F) &&
"Illegal formula generated!");
5302 ImplementSolution(Solution);
5305 void LSRInstance::print_factors_and_types(
raw_ostream &OS)
const {
5306 if (Factors.empty() && Types.empty())
return;
5308 OS <<
"LSR has identified the following interesting factors and types: ";
5311 for (int64_t Factor : Factors) {
5312 if (!First) OS <<
", ";
5314 OS <<
'*' << Factor;
5317 for (
Type *Ty : Types) {
5318 if (!First) OS <<
", ";
5320 OS <<
'(' << *Ty <<
')';
5325 void LSRInstance::print_fixups(
raw_ostream &OS)
const {
5326 OS <<
"LSR is examining the following fixup sites:\n";
5327 for (
const LSRUse &LU : Uses)
5328 for (
const LSRFixup &LF : LU.Fixups) {
5335 void LSRInstance::print_uses(
raw_ostream &OS)
const {
5336 OS <<
"LSR is examining the following uses:\n";
5337 for (
const LSRUse &LU : Uses) {
5341 for (
const Formula &F : LU.Formulae) {
5350 print_factors_and_types(OS);
5355 #if !defined(NDEBUG) || defined(LLVM_ENABLE_DUMP)
5363 class LoopStrengthReduce :
public LoopPass {
5367 LoopStrengthReduce();
5376 LoopStrengthReduce::LoopStrengthReduce() :
LoopPass(
ID) {
5380 void LoopStrengthReduce::getAnalysisUsage(
AnalysisUsage &AU)
const {
5403 bool Changed =
false;
5406 Changed |= LSRInstance(L, IU, SE, DT, LI, TTI).getChanged();
5431 auto &IU = getAnalysis<IVUsersWrapperPass>().getIU();
5432 auto &SE = getAnalysis<ScalarEvolutionWrapperPass>().getSE();
5433 auto &DT = getAnalysis<DominatorTreeWrapperPass>().getDomTree();
5434 auto &LI = getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
5435 const auto &TTI = getAnalysis<TargetTransformInfoWrapperPass>().getTTI(
5452 "Loop Strength Reduction",
false,
false)
Pass interface - Implemented by all 'passes'.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
void push_back(const T &Elt)
A parsed version of the target data layout string in and methods for querying it. ...
const_iterator end(StringRef path)
Get end iterator over path.
static bool isProfitableChain(IVChain &Chain, SmallPtrSetImpl< Instruction * > &Users, ScalarEvolution &SE, const TargetTransformInfo &TTI)
Return true if the number of registers needed for the chain is estimated to be less than the number r...
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.
size_type count() const
Returns the number of bits which are set.
GCNRegPressure max(const GCNRegPressure &P1, const GCNRegPressure &P2)
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"))
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 ...
const SCEV * getConstant(ConstantInt *V)
#define LLVM_DUMP_METHOD
Mark debug helper function definitions like dump() that should not be stripped from debug builds...
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
LLVMContext & getContext() const
bool isZero() const
Return true if the expression is a constant zero.
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.
Maximum length of the test input libFuzzer tries to guess a good value based on the corpus and reports it always prefer smaller inputs during the corpus shuffle When libFuzzer itself reports a bug this exit code will be used If indicates the maximal total time in seconds to run the fuzzer minimizes the provided crash input Use with tries to cleanse the provided crash input to make it contain fewer original bytes Use with exact_artifact_path to specify the output Experimental Use value profile to guide fuzzing Number of jobs to run If min(jobs, NumberOfCpuCores()/2)\" is used.") FUZZER_FLAG_INT(reload
static const size_t ComplexityLimit
Implements a dense probed hash-table based set.
The main scalar evolution driver.
virtual void getAnalysisUsage(AnalysisUsage &) const
getAnalysisUsage - This function should be overriden by passes that need analysis information to do t...
static cl::opt< bool > InsnsCost("lsr-insns-cost", cl::Hidden, cl::init(false), cl::desc("Add instruction count to a LSR cost model"))
static PointerType * get(Type *ElementType, unsigned AddressSpace)
This constructs a pointer to an object of the specified type in a numbered address space...
static const unsigned MaxIVUsers
MaxIVUsers is an arbitrary threshold that provides an early opportunitiy 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...
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void initializeLoopStrengthReducePass(PassRegistry &)
void setDebugType(const char *s)
int getFPMantissaWidth() const
Return the width of the mantissa of this type.
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)
const Function * getParent() const
Return the enclosing method, or null if none.
unsigned getNumSuccessors() const
Return the number of successors that this terminator has.
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
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.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
iv Induction Variable Users
void reserve(size_type N)
bool isTrueWhenEqual(CondCode Cond)
Return true if the specified condition returns true if the two operands to the condition are equal...
iterator end()
Get an iterator to the end of the SetVector.
bool isMinusOne() const
This function will return true iff every bit in this constant is set to true.
size_type size() const
Determine the number of elements in the SetVector.
BlockT * getHeader() const
This is the base class for unary cast operator classes.
const SCEV * getStart() const
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
A templated base class for SmallPtrSet which provides the typesafe interface that is common across al...
bool isNegative() const
Determine sign of this APInt.
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
AnalysisUsage & addRequired()
#define INITIALIZE_PASS_DEPENDENCY(depName)
bool isUnconditional() const
This class represents the LLVM 'select' instruction.
Option class for critical edge splitting.
const APInt & getValue() const
Return the constant as an APInt value reference.
void clearPostInc()
Disable all post-inc expansion.
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
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...
PassT::Result & getResult(IRUnitT &IR, ExtraArgTs...ExtraArgs)
Get the result of an analysis pass for a given IR unit.
This provides a uniform API for creating instructions and inserting them into a basic block: either a...
Reg
All possible values of the reg field in the ModR/M byte.
void getExitingBlocks(SmallVectorImpl< BlockT * > &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
int find_first() const
Returns the index of the first set bit, -1 if none of the bits are set.
void setName(const Twine &Name)
Change the name of the value.
Instruction * clone() const
Create a copy of 'this' instruction that is identical in all ways except the following: ...
op_iterator op_begin() const
This node represents multiplication of some number of SCEVs.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
This file implements a class to represent arbitrary precision integral constant values and operations...
LLVM_NODISCARD bool empty() const
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
auto reverse(ContainerTy &&C, typename std::enable_if< has_rbegin< ContainerTy >::value >::type *=nullptr) -> decltype(make_range(C.rbegin(), C.rend()))
bool insert(const value_type &X)
Insert a new element into the SetVector.
static bool isEqual(const Function &Caller, const Function &Callee)
This node represents a polynomial recurrence on the trip count of the specified loop.
iterator begin()
Get an iterator to the beginning of the SetVector.
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
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.
Base class for the actual dominator tree node.
AnalysisUsage & addPreservedID(const void *ID)
An instruction for storing to memory.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
auto count(R &&Range, const E &Element) -> typename std::iterator_traits< decltype(std::begin(Range))>::difference_type
Wrapper function around std::count to count the number of times an element Element occurs in the give...
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
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...
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
unsigned getMinSignedBits() const
Get the minimum bit size for this signed APInt.
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.
size_t getNumOperands() const
Class to represent pointers.
unsigned getNumIncomingValues() const
Return the number of incoming edges.
void replaceUsesOfWith(Value *From, Value *To)
Replace uses of one Value with another.
static bool DeleteTriviallyDeadInstructions(SmallVectorImpl< WeakTrackingVH > &DeadInsts)
If any of the instructions is the specified set are trivially dead, delete them and see if this makes...
iterator find(const_arg_type_t< KeyT > Val)
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
BasicBlock * SplitCriticalEdge(TerminatorInst *TI, unsigned SuccNum, const CriticalEdgeSplittingOptions &Options=CriticalEdgeSplittingOptions())
If this edge is a critical edge, insert a new node to split the critical edge.
static bool isCompatibleIVType(Value *LVal, Value *RVal)
Return true if we allow an IV chain to include both types.
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)
friend const_iterator end(StringRef path)
Get end iterator over path.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
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.
std::size_t countTrailingZeros(T Val, ZeroBehavior ZB=ZB_Width)
Count number of 0's from the least significant bit to the most stopping at the first 1...
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
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...
static void DoInitialMatch(const SCEV *S, Loop *L, SmallVectorImpl< const SCEV * > &Good, SmallVectorImpl< const SCEV * > &Bad, ScalarEvolution &SE)
Recursion helper for initialMatch.
This is an important class for using LLVM in a threaded context.
void setInsertPoint(Instruction *IP)
Set the current insertion point.
Type * getType() const
Return the LLVM type of this SCEV expression.
void SplitLandingPadPredecessors(BasicBlock *OrigBB, ArrayRef< BasicBlock * > Preds, const char *Suffix, const char *Suffix2, SmallVectorImpl< BasicBlock * > &NewBBs, DominatorTree *DT=nullptr, LoopInfo *LI=nullptr, bool PreserveLCSSA=false)
This method transforms the landing pad, OrigBB, by introducing two new basic blocks into the function...
Conditional or Unconditional Branch instruction.
This is an important base class in LLVM.
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator begin()
const SCEV * getOperand(unsigned i) const
int64_t getSExtValue() const
Get sign extended value.
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...
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.
static cl::opt< bool > EnablePhiElim("enable-lsr-phielim", cl::Hidden, cl::init(true), cl::desc("Enable LSR phi elimination"))
const DebugLoc & getDebugLoc() const
Return the debug location for this node as a DebugLoc.
Represent the analysis usage information of a pass.
static Type * getVoidTy(LLVMContext &C)
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
static bool isAlwaysFoldable(const TargetTransformInfo &TTI, LSRUse::KindType Kind, MemAccessTy AccessTy, GlobalValue *BaseGV, int64_t BaseOffset, bool HasBaseReg)
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang","erlang-compatible garbage collector")
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE,"Assign register bank of generic virtual registers", false, false) RegBankSelect
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
int find_next(unsigned Prev) const
Returns the index of the next set bit following the "Prev" bit.
for(unsigned i=0, e=MI->getNumOperands();i!=e;++i)
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.
APInt sdiv(const APInt &RHS) const
Signed division function for APInt.
Value * getOperand(unsigned i) const
self_iterator getIterator()
iterator_range< block_iterator > blocks()
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
Predicate getPredicate() const
Return the predicate for this instruction.
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)
Get the all ones value.
LLVM_NODISCARD bool empty() const
const APInt & getAPInt() const
bool isPointerTy() const
True if this is an instance of PointerType.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static wasm::ValType getType(const TargetRegisterClass *RC)
static bool isAddSExtable(const SCEVAddExpr *A, ScalarEvolution &SE)
Return true if the given add can be sign-extended without changing its value.
static cl::opt< bool > LSRExpNarrow("lsr-exp-narrow", cl::Hidden, cl::init(false), cl::desc("Narrow LSR complex solution using"" expectation of registers number"))
TargetTransformInfo & TTI
APInt srem(const APInt &RHS) const
Function for signed remainder operation.
void setChainedPhi(PHINode *PN)
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
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...
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.
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.
auto find(R &&Range, const T &Val) -> decltype(std::begin(Range))
Provide wrappers to std::find which take ranges instead of having to pass begin/end explicitly...
iterator_range< const_set_bits_iterator > set_bits() const
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
static cl::opt< bool > StressIVChain("stress-ivchain", cl::Hidden, cl::init(false), cl::desc("Stress test LSR IV chains"))
AnalysisUsage & addRequiredID(const void *ID)
Value * getOperandValToReplace() const
getOperandValToReplace - Return the Value of the operand in the user instruction that this IVStrideUs...
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.
Type * getType() const
All values are typed, get the type of this value.
constexpr size_t array_lengthof(T(&)[N])
Find the length of an array.
size_type count(ConstPtrType Ptr) const
count - Return 1 if the specified pointer is in the set, 0 otherwise.
const SCEV * getNoopOrSignExtend(const SCEV *V, Type *Ty)
Return a SCEV corresponding to a conversion of the input value to the specified type.
static bool isHighCostExpansion(const SCEV *S, SmallPtrSetImpl< const SCEV * > &Processed, ScalarEvolution &SE)
Check if expanding this expression is likely to incur significant cost.
void setIVIncInsertPos(const Loop *L, Instruction *Pos)
Set the current IV increment loop and position.
static Value * getWideOperand(Value *Oper)
IVChain logic must consistenctly peek base TruncInst operands, so wrap it in a convenient helper...
LLVM_NODISCARD T pop_back_val()
CHAIN = SC CHAIN, Imm128 - System call.
bool isStrictlyPositive() const
Determine if this APInt Value is positive.
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.
ConstantInt * getValue() const
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
size_t size() const
Returns the number of bits in this bitvector.
Class for arbitrary precision integers.
This node represents an addition of some number of SCEVs.
Value * getIncomingValueForBlock(const BasicBlock *BB) const
This class represents a signed maximum selection.
static bool isAddressUse(Instruction *Inst, Value *OperandVal)
Returns true if the specified instruction is using the specified value as an address.
typename SuperClass::iterator iterator
iterator_range< user_iterator > users()
DomTreeNodeBase< NodeT > * getNode(NodeT *BB) const
getNode - return the (Post)DominatorTree node for the specified basic block.
This class uses information about analyze scalars to rewrite expressions in canonical form...
hash_code hash_combine_range(InputIteratorT first, InputIteratorT last)
Compute a hash_code for a sequence of values.
static void clear(coro::Shape &Shape)
loop Loop Strength Reduction
iterator insert(iterator I, T &&Elt)
void append(in_iter in_start, in_iter in_end)
Add the specified range to the end of the SmallVector.
virtual bool runOnLoop(Loop *L, LPPassManager &LPM)=0
llvm_unreachable("Unknown RegBank!")
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
Virtual Register Rewriter
bool operator!=(uint64_t V1, const APInt &V2)
bool isAllOnesValue() const
Determine if all bits are set.
static unsigned getScalingFactorCost(const TargetTransformInfo &TTI, const LSRUse &LU, const Formula &F, const Loop &L)
LLVM_ATTRIBUTE_ALWAYS_INLINE iterator end()
Value * getCondition() const
void emplace_back(ArgTypes &&...Args)
bool isMinSignedValue() const
Determine if this is the smallest signed value.
This class represents an analyzed expression in the program.
Analysis pass that exposes the IVUsers for a loop.
Represents a single loop in the control flow graph.
bool isLandingPad() const
Return true if this basic block is a landing pad.
LLVM_ATTRIBUTE_ALWAYS_INLINE size_type size() const
bool hasOneUse() const
Return true if there is exactly one user of this value.
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...
INITIALIZE_PASS_BEGIN(LoopStrengthReduce,"loop-reduce","Loop Strength Reduction", false, false) INITIALIZE_PASS_END(LoopStrengthReduce
This class represents a cast unsigned integer to floating point.
static MemAccessTy getAccessType(const Instruction *Inst)
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)
INITIALIZE_PASS(HexagonGenMux,"hexagon-gen-mux","Hexagon generate mux instructions", false, false) void HexagonGenMux I isValid()
const Loop * getLoop() const
size_type count(const_arg_type_t< ValueT > V) const
Return 1 if the specified key is in the set, 0 otherwise.
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.
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
const SCEV * getBackedgeTakenCount(const Loop *L)
If the specified loop has a predictable backedge-taken count, return it, otherwise return a SCEVCould...
This class represents a cast from signed integer to floating point.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
unsigned getSCEVType() const
const SCEV * denormalizeForPostIncUse(const SCEV *S, const PostIncLoopSet &Loops, ScalarEvolution &SE)
Denormalize S to be post-increment for all loops present in Loops.
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
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.
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.
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.
This class implements an extremely fast bulk output stream that can only output to a stream...
bool isInsertedInstruction(Instruction *I) const
Return true if the specified instruction was inserted by the code rewriter.
void disableCanonicalMode()
Disable the behavior of expanding expressions in canonical form rather than in a more literal form...
const SCEV * getUnknown(Value *V)
The legacy pass manager's analysis pass to compute loop information.
op_iterator op_end() const
A container for analyses that lazily runs them and caches their results.
Legacy analysis pass which computes a DominatorTree.
void sort(Policy policy, RandomAccessIterator Start, RandomAccessIterator End, const Comparator &Comp=Comparator())
bool operator==(uint64_t V1, const APInt &V2)
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.
const TerminatorInst * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
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.
void setIncomingValue(unsigned i, Value *V)
auto find_if(R &&Range, UnaryPredicate P) -> decltype(std::begin(Range))
Provide wrappers to std::find_if which take ranges instead of having to pass begin/end explicitly...
const Instruction * getFirstNonPHI() const
Returns a pointer to the first instruction in this block that is not a PHINode instruction.
void setPostInc(const PostIncLoopSet &L)
Enable post-inc expansion for addrecs referring to the given loops.
int64_t getSExtValue() const
Return the constant as a 64-bit integer value after it has been sign extended as appropriate for the ...
bool isSafeToExpand(const SCEV *S, ScalarEvolution &SE)
Return true if the given expression is safe to expand in the sense that all materialized values are s...
static bool ReduceLoopStrength(Loop *L, IVUsers &IU, ScalarEvolution &SE, DominatorTree &DT, LoopInfo &LI, const TargetTransformInfo &TTI)
unsigned getPointerAddressSpace() const
Get the address space of this pointer or pointer vector type.
unsigned getLoopDepth() const
Return the nesting level of this loop.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
void moveBefore(BasicBlock *MovePos)
Unlink this basic block from its current function and insert it into the function that MovePos lives ...
const BasicBlock * getParent() const
bool isOne() const
This is just a convenience method to make client code smaller for a common case.
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.
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 properlyDominates(const DomTreeNodeBase< NodeT > *A, const DomTreeNodeBase< NodeT > *B) const
properlyDominates - Returns true iff A dominates B and A != B.
bool is_contained(R &&Range, const E &Element)
Wrapper function around std::find to detect if an element exists in a container.