91 #define DEBUG_TYPE "indvars" 93 STATISTIC(NumWidened ,
"Number of indvars widened");
94 STATISTIC(NumReplaced ,
"Number of exit values replaced");
95 STATISTIC(NumLFTR ,
"Number of loop exit tests replaced");
96 STATISTIC(NumElimExt ,
"Number of IV sign/zero extends eliminated");
97 STATISTIC(NumElimIV ,
"Number of congruent IVs eliminated");
104 cl::desc(
"Verify the ScalarEvolution result after running indvars"));
110 cl::desc(
"Choose the strategy to replace exit value in IndVarSimplify"),
113 "only replace exit value when the cost is cheap"),
115 "only replace exit values when loop def likely dead"),
117 "always replace exit value whenever possible")));
121 cl::desc(
"Use post increment control-dependent ranges in IndVarSimplify"),
126 cl::desc(
"Disable Linear Function Test Replace optimization"));
130 cl::desc(
"Predicate conditions in read only loops"));
136 class IndVarSimplify {
146 bool isValidRewrite(
Value *FromVal,
Value *ToVal);
149 bool rewriteNonIntegerIVs(
Loop *L);
160 bool rewriteFirstIterationLoopExitValues(
Loop *L);
164 const SCEV *ExitCount,
167 bool sinkUnusedInvariants(
Loop *L);
173 : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
184 bool IndVarSimplify::isValidRewrite(
Value *FromVal,
Value *ToVal) {
195 Value *FromPtr = FromVal;
196 Value *ToPtr = ToVal;
197 if (
auto *
GEP = dyn_cast<GEPOperator>(FromVal)) {
198 FromPtr =
GEP->getPointerOperand();
200 if (
auto *
GEP = dyn_cast<GEPOperator>(ToVal)) {
201 ToPtr =
GEP->getPointerOperand();
203 if (FromPtr != FromVal || ToPtr != ToVal) {
205 if (FromPtr == ToPtr)
219 const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
220 const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
221 if (FromBase == ToBase)
224 LLVM_DEBUG(
dbgs() <<
"INDVARS: GEP rewrite bail out " << *FromBase
225 <<
" != " << *ToBase <<
"\n");
271 assert(DT->
dominates(DefI, InsertPt) &&
"def does not dominate all uses");
276 for (
auto *DTN = (*DT)[InsertPt->
getParent()]; DTN; DTN = DTN->getIDom())
278 return DTN->getBlock()->getTerminator();
289 bool isExact =
false;
308 bool IndVarSimplify::handleFloatingPointIV(
Loop *L,
PHINode *PN) {
310 unsigned BackEdge = IncomingEdge^1;
316 if (!InitValueVal || !
ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
322 if (Incr ==
nullptr || Incr->getOpcode() != Instruction::FAdd)
return false;
328 if (IncValueVal ==
nullptr || Incr->
getOperand(0) != PN ||
336 if (IncrUse == Incr->user_end())
return false;
338 if (IncrUse != Incr->user_end())
return false;
365 if (ExitValueVal ==
nullptr ||
372 default:
return false;
405 if (InitValue >= ExitValue)
412 if (++Range == 0)
return false;
415 unsigned Leftover = Range %
uint32_t(IncValue);
426 if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
431 if (InitValue <= ExitValue)
438 if (++Range == 0)
return false;
441 unsigned Leftover = Range %
uint32_t(-IncValue);
452 if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
502 bool IndVarSimplify::rewriteNonIntegerIVs(
Loop *L) {
512 bool Changed =
false;
513 for (
unsigned i = 0,
e = PHIs.
size(); i !=
e; ++i)
514 if (
PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
515 Changed |= handleFloatingPointIV(L, PN);
542 : PN(P), Ith(I), Val(V), HighCost(H) {}
552 bool IndVarSimplify::hasHardUserWithinLoop(
const Loop *L,
const Instruction *
I)
const {
557 while (!WorkList.
empty()) {
566 for (
auto U : Curr->
users()) {
567 auto *UI = cast<Instruction>(U);
568 if (Visited.
insert(UI).second)
588 "Indvars did not preserve LCSSA!");
607 while ((PN = dyn_cast<PHINode>(BBI++))) {
611 if (!SE->isSCEVable(PN->
getType()))
622 for (
unsigned i = 0; i != NumPreds; ++i) {
626 if (!isa<Instruction>(InVal))
645 if (isa<SCEVCouldNotCompute>(ExitValue) ||
646 !SE->isLoopInvariant(ExitValue, L) ||
653 if (isa<SCEVCouldNotCompute>(ExitCount))
655 if (
auto *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Inst)))
656 if (AddRec->getLoop() == L)
657 ExitValue = AddRec->evaluateAtIteration(ExitCount, *SE);
658 if (isa<SCEVCouldNotCompute>(ExitValue) ||
659 !SE->isLoopInvariant(ExitValue, L) ||
669 if (ReplaceExitValue != AlwaysRepl &&
670 !isa<SCEVConstant>(ExitValue) && !isa<SCEVUnknown>(ExitValue) &&
671 hasHardUserWithinLoop(L, Inst))
679 <<
" LoopVal = " << *Inst <<
"\n");
681 if (!isValidRewrite(Inst, ExitVal)) {
682 DeadInsts.push_back(ExitVal);
690 if (
auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
691 if (
auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
693 assert(EVL->contains(L) &&
"LCSSA breach detected!");
702 bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
704 bool Changed =
false;
706 for (
const RewritePhi &Phi : RewritePhiSet) {
708 Value *ExitVal = Phi.Val;
712 if (ReplaceExitValue ==
OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
713 DeadInsts.push_back(ExitVal);
725 DeadInsts.push_back(Inst);
729 LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
750 bool IndVarSimplify::rewriteFirstIterationLoopExitValues(
Loop *L) {
757 bool MadeAnyChanges =
false;
758 for (
auto *ExitBB : ExitBlocks) {
761 for (
PHINode &PN : ExitBB->phis()) {
763 IncomingValIdx !=
E; ++IncomingValIdx) {
778 Value *Cond =
nullptr;
779 if (
auto *BI = dyn_cast<BranchInst>(TermInst)) {
782 Cond = BI->getCondition();
783 }
else if (
auto *
SI = dyn_cast<SwitchInst>(TermInst))
784 Cond =
SI->getCondition();
794 if (!ExitVal || ExitVal->getParent() != L->
getHeader())
801 assert(LoopPreheader &&
"Invalid loop");
802 int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
803 if (PreheaderIdx != -1) {
805 "ExitVal must be in loop header");
806 MadeAnyChanges =
true;
808 ExitVal->getIncomingValue(PreheaderIdx));
813 return MadeAnyChanges;
819 bool IndVarSimplify::canLoopBeDeleted(
834 if (ExitBlocks.
size() != 1 || ExitingBlocks.
size() != 1)
839 while (
PHINode *
P = dyn_cast<PHINode>(BI)) {
840 Value *Incoming =
P->getIncomingValueForBlock(ExitingBlocks[0]);
846 for (
const RewritePhi &Phi : RewritePhiSet) {
847 unsigned i = Phi.Ith;
848 if (Phi.PN ==
P && (Phi.PN)->getIncomingValue(i) == Incoming) {
855 if (!found && (I = dyn_cast<Instruction>(Incoming)))
862 for (
auto *BB : L->
blocks())
884 Type *WidestNativeType =
nullptr;
887 bool IsSigned =
false;
897 bool IsSigned = Cast->
getOpcode() == Instruction::SExt;
898 if (!IsSigned && Cast->
getOpcode() != Instruction::ZExt)
911 if (NarrowIVWidth >= Width)
927 if (!WI.WidestNativeType) {
929 WI.IsSigned = IsSigned;
934 if (WI.IsSigned != IsSigned)
946 struct NarrowIVDefUse {
954 bool NeverNegative =
false;
958 : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
959 NeverNegative(NeverNegative) {}
984 const SCEV *WideIncExpr =
nullptr;
990 enum ExtendKind { ZeroExtended, SignExtended,
Unknown };
1008 DefUserPair
Key(Def, UseI);
1009 auto It = PostIncRangeInfos.
find(Key);
1010 return It == PostIncRangeInfos.
end()
1015 void calculatePostIncRanges(
PHINode *OrigPhi);
1019 DefUserPair
Key(Def, UseI);
1020 auto It = PostIncRangeInfos.
find(Key);
1021 if (It == PostIncRangeInfos.
end())
1022 PostIncRangeInfos.
insert({Key, R});
1031 : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1033 HasGuards(HasGuards), DeadInsts(DI) {
1035 ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
1041 Value *createExtendInst(
Value *NarrowOper,
Type *WideType,
bool IsSigned,
1045 Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1047 Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1051 using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1053 WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1055 WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1057 const SCEV *getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1058 unsigned OpCode)
const;
1062 bool widenLoopCompare(NarrowIVDefUse DU);
1063 bool widenWithVariantLoadUse(NarrowIVDefUse DU);
1064 void widenWithVariantLoadUseCodegen(NarrowIVDefUse DU);
1071 Value *WidenIV::createExtendInst(
Value *NarrowOper,
Type *WideType,
1081 return IsSigned ? Builder.
CreateSExt(NarrowOper, WideType) :
1088 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1090 unsigned Opcode = DU.NarrowUse->getOpcode();
1095 case Instruction::Mul:
1096 case Instruction::UDiv:
1097 case Instruction::Sub:
1098 return cloneArithmeticIVUser(DU, WideAR);
1100 case Instruction::And:
1101 case Instruction::Or:
1102 case Instruction::Xor:
1103 case Instruction::Shl:
1104 case Instruction::LShr:
1105 case Instruction::AShr:
1106 return cloneBitwiseIVUser(DU);
1110 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1115 LLVM_DEBUG(
dbgs() <<
"Cloning bitwise IVUser: " << *NarrowUse <<
"\n");
1121 bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1124 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1125 IsSigned, NarrowUse);
1128 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1129 IsSigned, NarrowUse);
1131 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1135 Builder.Insert(WideBO);
1136 WideBO->copyIRFlags(NarrowBO);
1140 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1146 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1148 unsigned IVOpIdx = (NarrowUse->
getOperand(0) == NarrowDef) ? 0 : 1;
1159 auto GuessNonIVOperand = [&](
bool SignExt) {
1160 const SCEV *WideLHS;
1161 const SCEV *WideRHS;
1163 auto GetExtend = [
this, SignExt](
const SCEV *S,
Type *Ty) {
1165 return SE->getSignExtendExpr(S, Ty);
1166 return SE->getZeroExtendExpr(S, Ty);
1170 WideLHS = SE->getSCEV(WideDef);
1172 WideRHS = GetExtend(NarrowRHS, WideType);
1175 WideLHS = GetExtend(NarrowLHS, WideType);
1176 WideRHS = SE->getSCEV(WideDef);
1180 const SCEV *WideUse =
nullptr;
1187 WideUse = SE->getAddExpr(WideLHS, WideRHS);
1190 case Instruction::Mul:
1191 WideUse = SE->getMulExpr(WideLHS, WideRHS);
1194 case Instruction::UDiv:
1195 WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1198 case Instruction::Sub:
1199 WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1203 return WideUse == WideAR;
1206 bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1207 if (!GuessNonIVOperand(SignExtend)) {
1208 SignExtend = !SignExtend;
1209 if (!GuessNonIVOperand(SignExtend))
1215 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1216 SignExtend, NarrowUse);
1219 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1220 SignExtend, NarrowUse);
1222 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1227 Builder.Insert(WideBO);
1228 WideBO->copyIRFlags(NarrowBO);
1232 WidenIV::ExtendKind WidenIV::getExtendKind(
Instruction *I) {
1233 auto It = ExtendKindMap.find(I);
1234 assert(It != ExtendKindMap.end() &&
"Instruction not yet extended!");
1238 const SCEV *WidenIV::getSCEVByOpCode(
const SCEV *LHS,
const SCEV *RHS,
1239 unsigned OpCode)
const {
1241 return SE->getAddExpr(LHS, RHS);
1242 if (OpCode == Instruction::Sub)
1243 return SE->getMinusSCEV(LHS, RHS);
1244 if (OpCode == Instruction::Mul)
1245 return SE->getMulExpr(LHS, RHS);
1255 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1257 const unsigned OpCode = DU.NarrowUse->getOpcode();
1260 OpCode != Instruction::Mul)
1265 const unsigned ExtendOperIdx =
1266 DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1267 assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef &&
"bad DU");
1269 const SCEV *ExtendOperExpr =
nullptr;
1271 cast<OverflowingBinaryOperator>(DU.NarrowUse);
1272 ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1274 ExtendOperExpr = SE->getSignExtendExpr(
1275 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1277 ExtendOperExpr = SE->getZeroExtendExpr(
1278 SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1287 const SCEV *lhs = SE->getSCEV(DU.WideDef);
1288 const SCEV *rhs = ExtendOperExpr;
1292 if (ExtendOperIdx == 0)
1297 if (!AddRec || AddRec->
getLoop() != L)
1300 return {AddRec, ExtKind};
1308 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1309 if (!SE->isSCEVable(DU.NarrowUse->getType()))
1312 const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1313 if (SE->getTypeSizeInBits(NarrowExpr->
getType()) >=
1314 SE->getTypeSizeInBits(WideType)) {
1320 const SCEV *WideExpr;
1322 if (DU.NeverNegative) {
1323 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1324 if (isa<SCEVAddRecExpr>(WideExpr))
1325 ExtKind = SignExtended;
1327 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1328 ExtKind = ZeroExtended;
1330 }
else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1331 WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1332 ExtKind = SignExtended;
1334 WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1335 ExtKind = ZeroExtended;
1338 if (!AddRec || AddRec->
getLoop() != L)
1340 return {AddRec, ExtKind};
1349 LLVM_DEBUG(
dbgs() <<
"INDVARS: Truncate IV " << *DU.WideDef <<
" for user " 1350 << *DU.NarrowUse <<
"\n");
1353 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1359 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1378 bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1379 if (!(DU.NeverNegative || IsSigned == Cmp->
isSigned()))
1383 unsigned CastWidth = SE->getTypeSizeInBits(Op->
getType());
1384 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1385 assert(CastWidth <= IVWidth &&
"Unexpected width while widening compare.");
1392 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1395 if (CastWidth < IVWidth) {
1396 Value *ExtOp = createExtendInst(Op, WideType, Cmp->
isSigned(), Cmp);
1397 DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1415 bool WidenIV::widenWithVariantLoadUse(NarrowIVDefUse DU) {
1421 const unsigned OpCode = NarrowUse->
getOpcode();
1424 OpCode != Instruction::Mul)
1429 unsigned ExtendOperIdx = DU.NarrowUse->getOperand(0) == NarrowDef ? 1 : 0;
1430 assert(DU.NarrowUse->getOperand(1 - ExtendOperIdx) == DU.NarrowDef &&
1433 const SCEV *ExtendOperExpr =
nullptr;
1435 cast<OverflowingBinaryOperator>(NarrowUse);
1436 ExtendKind ExtKind = getExtendKind(NarrowDef);
1438 ExtendOperExpr = SE->getSignExtendExpr(
1439 SE->getSCEV(NarrowUse->
getOperand(ExtendOperIdx)), WideType);
1441 ExtendOperExpr = SE->getZeroExtendExpr(
1442 SE->getSCEV(NarrowUse->
getOperand(ExtendOperIdx)), WideType);
1453 const SCEV *Op1 = SE->getSCEV(WideDef);
1455 if (!AddRecOp1 || AddRecOp1->
getLoop() != L)
1458 if (ExtKind == SignExtended) {
1459 if (!isa<SCEVSignExtendExpr>(ExtendOperExpr))
1462 if (!isa<SCEVZeroExtendExpr>(ExtendOperExpr))
1466 if (ExtKind == SignExtended) {
1467 for (Use &U : NarrowUse->
uses()) {
1469 if (!User || User->
getType() != WideType)
1473 for (Use &U : NarrowUse->
uses()) {
1475 if (!User || User->
getType() != WideType)
1485 void WidenIV::widenWithVariantLoadUseCodegen(NarrowIVDefUse DU) {
1490 ExtendKind ExtKind = getExtendKind(NarrowDef);
1492 LLVM_DEBUG(
dbgs() <<
"Cloning arithmetic IVUser: " << *NarrowUse <<
"\n");
1497 : createExtendInst(NarrowUse->
getOperand(0), WideType,
1498 ExtKind, NarrowUse);
1501 : createExtendInst(NarrowUse->
getOperand(1), WideType,
1502 ExtKind, NarrowUse);
1504 auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1508 Builder.Insert(WideBO);
1509 WideBO->copyIRFlags(NarrowBO);
1511 if (ExtKind == SignExtended)
1512 ExtendKindMap[NarrowUse] = SignExtended;
1514 ExtendKindMap[NarrowUse] = ZeroExtended;
1517 if (ExtKind == SignExtended) {
1518 for (Use &U : NarrowUse->
uses()) {
1520 if (User && User->
getType() == WideType) {
1521 LLVM_DEBUG(
dbgs() <<
"INDVARS: eliminating " << *User <<
" replaced by " 1522 << *WideBO <<
"\n");
1525 DeadInsts.emplace_back(User);
1529 for (Use &U : NarrowUse->
uses()) {
1531 if (User && User->
getType() == WideType) {
1532 LLVM_DEBUG(
dbgs() <<
"INDVARS: eliminating " << *User <<
" replaced by " 1533 << *WideBO <<
"\n");
1536 DeadInsts.emplace_back(User);
1545 assert(ExtendKindMap.count(DU.NarrowDef) &&
1546 "Should already know the kind of extension used to widen NarrowDef");
1549 if (
PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1550 if (LI->getLoopFor(UsePhi->getParent()) != L) {
1554 if (UsePhi->getNumOperands() != 1)
1560 if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1564 PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() +
".wide",
1566 WidePhi->
addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1568 Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1570 DeadInsts.emplace_back(UsePhi);
1571 LLVM_DEBUG(
dbgs() <<
"INDVARS: Widen lcssa phi " << *UsePhi <<
" to " 1572 << *WidePhi <<
"\n");
1580 auto canWidenBySExt = [&]() {
1581 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1583 auto canWidenByZExt = [&]() {
1584 return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1588 if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1589 (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1590 Value *NewDef = DU.WideDef;
1591 if (DU.NarrowUse->getType() != WideType) {
1592 unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1593 unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1594 if (CastWidth < IVWidth) {
1597 NewDef = Builder.
CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1604 <<
" not wide enough to subsume " << *DU.NarrowUse
1606 DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1607 NewDef = DU.NarrowUse;
1610 if (NewDef != DU.NarrowUse) {
1612 <<
" replaced by " << *DU.WideDef <<
"\n");
1614 DU.NarrowUse->replaceAllUsesWith(NewDef);
1615 DeadInsts.emplace_back(DU.NarrowUse);
1628 WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1629 if (!WideAddRec.first)
1630 WideAddRec = getWideRecurrence(DU);
1632 assert((WideAddRec.first ==
nullptr) == (WideAddRec.second ==
Unknown));
1633 if (!WideAddRec.first) {
1636 if (widenLoopCompare(DU))
1644 if (widenWithVariantLoadUse(DU)) {
1645 widenWithVariantLoadUseCodegen(DU);
1657 assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1658 "SCEV is not expected to evaluate a block terminator");
1663 if (WideAddRec.first == WideIncExpr &&
1667 WideUse = cloneIVUser(DU, WideAddRec.first);
1676 if (WideAddRec.first != SE->getSCEV(WideUse)) {
1677 LLVM_DEBUG(
dbgs() <<
"Wide use expression mismatch: " << *WideUse <<
": " 1678 << *SE->getSCEV(WideUse) <<
" != " << *WideAddRec.first
1680 DeadInsts.emplace_back(WideUse);
1688 ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1695 const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1696 bool NonNegativeDef =
1698 SE->getConstant(NarrowSCEV->
getType(), 0));
1703 if (!Widened.insert(NarrowUser).second)
1706 bool NonNegativeUse =
false;
1707 if (!NonNegativeDef) {
1709 if (
auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1710 NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1713 NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1714 NonNegativeDef || NonNegativeUse);
1733 const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1734 ? SE->getSignExtendExpr(AddRec, WideType)
1735 : SE->getZeroExtendExpr(AddRec, WideType);
1737 assert(SE->getEffectiveSCEVType(WideIVExpr->
getType()) == WideType &&
1738 "Expect the new IV expression to preserve its type");
1742 if (!AddRec || AddRec->
getLoop() != L)
1751 "Loop header phi recurrence inputs do not dominate the loop");
1763 if (UsePostIncrementRanges)
1764 calculatePostIncRanges(OrigPhi);
1771 WidePhi = cast<PHINode>(Rewriter.
expandCodeFor(AddRec, WideType, InsertPt));
1779 cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1780 WideIncExpr = SE->getSCEV(WideInc);
1784 cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1792 assert(Widened.empty() && NarrowIVUsers.empty() &&
"expect initial state" );
1794 Widened.insert(OrigPhi);
1795 pushNarrowIVUsers(OrigPhi, WidePhi);
1797 while (!NarrowIVUsers.empty()) {
1798 NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1806 pushNarrowIVUsers(DU.NarrowUse, WideUse);
1809 if (DU.NarrowDef->use_empty())
1810 DeadInsts.emplace_back(DU.NarrowDef);
1821 void WidenIV::calculatePostIncRange(
Instruction *NarrowDef,
1825 Value *NarrowDefLHS;
1826 const APInt *NarrowDefRHS;
1832 auto UpdateRangeFromCondition = [&] (
Value *Condition,
1843 auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1844 auto CmpConstrainedLHSRange =
1846 auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
1849 updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1852 auto UpdateRangeFromGuards = [&](
Instruction *Ctx) {
1857 Ctx->getParent()->rend())) {
1859 if (
match(&I, m_Intrinsic<Intrinsic::experimental_guard>(
m_Value(C))))
1860 UpdateRangeFromCondition(C,
true);
1864 UpdateRangeFromGuards(NarrowUser);
1869 if (!DT->isReachableFromEntry(NarrowUserBB))
1872 for (
auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1874 DTB = DTB->getIDom()) {
1875 auto *BB = DTB->getBlock();
1877 UpdateRangeFromGuards(TI);
1880 if (!BI || !BI->isConditional())
1884 auto *FalseSuccessor = BI->getSuccessor(1);
1886 auto DominatesNarrowUser = [
this, NarrowUser] (
BasicBlockEdge BBE) {
1887 return BBE.isSingleEdge() &&
1888 DT->dominates(BBE, NarrowUser->
getParent());
1892 UpdateRangeFromCondition(BI->getCondition(),
true);
1895 UpdateRangeFromCondition(BI->getCondition(),
false);
1900 void WidenIV::calculatePostIncRanges(
PHINode *OrigPhi) {
1906 while (!Worklist.
empty()) {
1909 for (Use &U : NarrowDef->
uses()) {
1910 auto *NarrowUser = cast<Instruction>(U.getUser());
1913 auto *NarrowUserLoop = (*LI)[NarrowUser->
getParent()];
1914 if (!NarrowUserLoop || !L->
contains(NarrowUserLoop))
1917 if (!Visited.
insert(NarrowUser).second)
1922 calculatePostIncRange(NarrowDef, NarrowUser);
1937 class IndVarSimplifyVisitor :
public IVVisitor {
1948 : SE(SCEV), TTI(TTI), IVPhi(IV) {
1950 WI.NarrowIV = IVPhi;
1964 bool IndVarSimplify::simplifyAndExtend(
Loop *L,
1969 auto *GuardDecl = L->
getBlocks()[0]->getModule()->getFunction(
1971 bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1981 bool Changed =
false;
1982 while (!LoopPhis.
empty()) {
1993 IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1998 if (Visitor.WI.WidestNativeType) {
2001 }
while(!LoopPhis.
empty());
2004 WidenIV Widener(WideIVs.
back(), LI, SE, DT, DeadInsts, HasGuards);
2005 if (
PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
2028 case Instruction::Sub:
2030 case Instruction::GetElementPtr:
2045 if (IncI->
getOpcode() == Instruction::GetElementPtr)
2067 return ICmp->
getOperand(0) == V || ICmp->getOperand(1) == V;
2139 while (!Worklist.
empty()) {
2151 if (KnownPoison.
insert(I).second)
2166 if (isa<Constant>(V))
2167 return !isa<UndefValue>(V);
2210 if (U != Cond && U != IncV)
return false;
2213 if (U != Cond && U != Phi)
return false;
2233 if (!Step || !Step->
isOne())
2249 const SCEV *BECount,
2257 const SCEV *BestInit =
nullptr;
2259 assert(LatchBlock &&
"Must be in simplified form");
2271 const auto *AR = cast<SCEVAddRecExpr>(SE->
getSCEV(Phi));
2306 if (BestPhi && !
AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2320 else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->
getType()))
2333 const SCEV *ExitCount,
bool UsePostInc,
Loop *L,
2358 "Computed iteration count is not loop invariant!");
2363 cast<PointerType>(IndVar->
getType())
2364 ->getElementType())->isOne() &&
2365 "unit stride pointer IV must be i8*");
2393 if (isa<SCEVConstant>(IVInit) && isa<SCEVConstant>(ExitCount))
2406 "Computed iteration count is not loop invariant!");
2422 bool IndVarSimplify::
2424 const SCEV *ExitCount,
2432 Value *CmpIndVar = IndVar;
2433 bool UsePostInc =
false;
2443 bool SafeToPostInc =
2447 if (SafeToPostInc) {
2465 if (
auto *BO = dyn_cast<BinaryOperator>(IncVar)) {
2466 const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IncVar));
2467 if (BO->hasNoUnsignedWrap())
2469 if (BO->hasNoSignedWrap())
2474 IndVar, ExitingBB, ExitCount, UsePostInc, L, Rewriter, SE);
2477 "genLoopLimit missed a cast");
2482 if (L->
contains(BI->getSuccessor(0)))
2491 if (
auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2499 unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->
getType());
2500 unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->
getType());
2501 if (CmpIndVarSize > ExitCntSize) {
2510 bool Extended =
false;
2511 const SCEV *IV = SE->getSCEV(CmpIndVar);
2512 const SCEV *TruncatedIV = SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2514 const SCEV *ZExtTrunc =
2515 SE->getZeroExtendExpr(TruncatedIV, CmpIndVar->
getType());
2517 if (ZExtTrunc == IV) {
2522 const SCEV *SExtTrunc =
2523 SE->getSignExtendExpr(TruncatedIV, CmpIndVar->
getType());
2524 if (SExtTrunc == IV) {
2538 LLVM_DEBUG(
dbgs() <<
"INDVARS: Rewriting loop exit condition to:\n" 2539 <<
" LHS:" << *CmpIndVar <<
'\n' 2542 <<
" RHS:\t" << *ExitCnt <<
"\n" 2543 <<
"ExitCount:\t" << *ExitCount <<
"\n" 2544 <<
" was: " << *BI->getCondition() <<
"\n");
2547 Value *OrigCond = BI->getCondition();
2553 BI->setCondition(Cond);
2554 DeadInsts.push_back(OrigCond);
2567 bool IndVarSimplify::sinkUnusedInvariants(
Loop *L) {
2569 if (!ExitBlock)
return false;
2572 if (!Preheader)
return false;
2574 bool MadeAnyChanges =
false;
2577 while (I != Preheader->
begin()) {
2580 if (isa<PHINode>(I))
2593 if (isa<DbgInfoIntrinsic>(I))
2604 if (isa<AllocaInst>(I))
2609 bool UsedInLoop =
false;
2610 for (Use &U : I->
uses()) {
2613 if (
PHINode *
P = dyn_cast<PHINode>(User)) {
2616 UseBB =
P->getIncomingBlock(i);
2618 if (UseBB == Preheader || L->
contains(UseBB)) {
2632 if (I != Preheader->
begin()) {
2636 }
while (isa<DbgInfoIntrinsic>(I) && I != Preheader->
begin());
2638 if (isa<DbgInfoIntrinsic>(I) && I == Preheader->
begin())
2644 MadeAnyChanges =
true;
2650 return MadeAnyChanges;
2666 for (
BasicBlock *ExitingBB : ExitingBlocks) {
2668 if (isa<SCEVCouldNotCompute>(ExitCount))
2671 if (!isa<SCEVCouldNotCompute>(ExitCount)) {
2673 "We should only have known counts for exiting blocks that " 2678 if (ExitCounts.
empty())
2705 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2706 if (isa<SCEVCouldNotCompute>(ExitCount))
2710 ExitingBlocks.
erase(NewEnd, ExitingBlocks.
end());
2712 if (ExitingBlocks.
empty())
2717 if (isa<SCEVCouldNotCompute>(MaxExitCount))
2728 if (DT->properlyDominates(A, B))
return true;
2729 if (DT->properlyDominates(B, A))
return false;
2733 for (
unsigned i = 1; i < ExitingBlocks.
size(); i++) {
2734 assert(DT->dominates(ExitingBlocks[i-1], ExitingBlocks[i]));
2738 auto FoldExit = [&](
BasicBlock *ExitingBB,
bool IsTaken) {
2743 IsTaken ? ExitIfTrue : !ExitIfTrue);
2745 if (OldCond->use_empty())
2746 DeadInsts.push_back(OldCond);
2749 bool Changed =
false;
2751 for (
BasicBlock *ExitingBB : ExitingBlocks) {
2752 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2753 assert(!isa<SCEVCouldNotCompute>(ExitCount) &&
"checked above");
2760 if (ExitCount->
isZero()) {
2761 FoldExit(ExitingBB,
true);
2775 ExitCount = SE->getNoopOrZeroExtend(ExitCount, WiderType);
2776 MaxExitCount = SE->getNoopOrZeroExtend(MaxExitCount, WiderType);
2782 MaxExitCount, ExitCount)) {
2783 FoldExit(ExitingBB,
false);
2792 if (!DominatingExitCounts.
insert(ExitCount).second) {
2793 FoldExit(ExitingBB,
false);
2812 bool Changed =
false;
2823 if (!LoopPredication)
2826 if (!SE->hasLoopInvariantBackedgeTakenCount(L))
2832 const SCEV *ExactBTC = SE->getBackedgeTakenCount(L);
2833 if (isa<SCEVCouldNotCompute>(ExactBTC) ||
2834 !SE->isLoopInvariant(ExactBTC, L) ||
2863 if (!ExitBlock->
phis().empty())
2866 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2867 assert(!isa<SCEVCouldNotCompute>(ExactBTC) &&
"implied by having exact trip count");
2868 if (!SE->isLoopInvariant(ExitCount, L) ||
2891 if (DT->properlyDominates(A, B))
return true;
2892 if (DT->properlyDominates(B, A))
return false;
2898 for (
unsigned i = 1; i < ExitingBlocks.
size(); i++)
2899 if (!DT->dominates(ExitingBlocks[i-1], ExitingBlocks[i]))
2904 for (
unsigned i = 0,
e = ExitingBlocks.
size(); i <
e; i++)
2905 if (BadExit(ExitingBlocks[i])) {
2910 if (ExitingBlocks.
empty())
2947 Value *ExactBTCV =
nullptr;
2948 for (
BasicBlock *ExitingBB : ExitingBlocks) {
2949 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
2953 if (ExitCount == ExactBTC) {
2954 NewCond = L->
contains(BI->getSuccessor(0)) ?
2955 B.getFalse() : B.getTrue();
2960 Value *RHS = ExactBTCV;
2963 ECV = B.CreateZExt(ECV, WiderTy);
2964 RHS = B.CreateZExt(RHS, WiderTy);
2966 auto Pred = L->
contains(BI->getSuccessor(0)) ?
2968 NewCond = B.CreateICmp(Pred, ECV, RHS);
2970 Value *OldCond = BI->getCondition();
2971 BI->setCondition(NewCond);
2973 DeadInsts.push_back(OldCond);
2984 bool IndVarSimplify::run(
Loop *L) {
2987 "LCSSA required to run indvars!");
2988 bool Changed =
false;
3004 const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
3009 Changed |= rewriteNonIntegerIVs(L);
3024 Changed |= simplifyAndExtend(L, Rewriter, LI);
3031 Changed |= rewriteLoopExitValues(L, Rewriter);
3037 if (optimizeLoopExits(L, Rewriter)) {
3045 if (predicateLoopExits(L, Rewriter)) {
3056 for (
BasicBlock *ExitingBB : ExitingBlocks) {
3070 const SCEV *ExitCount = SE->getExitCount(L, ExitingBB);
3071 if (isa<SCEVCouldNotCompute>(ExitCount))
3101 Changed |= linearFunctionTestReplace(L, ExitingBB,
3113 while (!DeadInsts.empty())
3115 dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
3122 Changed |= sinkUnusedInvariants(L);
3127 Changed |= rewriteFirstIterationLoopExitValues(L);
3134 "Indvars did not preserve LCSSA!");
3140 if (
VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
3142 const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
3143 if (SE->getTypeSizeInBits(BackedgeTakenCount->
getType()) <
3144 SE->getTypeSizeInBits(NewBECount->
getType()))
3145 NewBECount = SE->getTruncateOrNoop(NewBECount,
3146 BackedgeTakenCount->
getType());
3148 BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
3151 NewBECount) &&
"indvars must preserve SCEV");
3164 IndVarSimplify IVS(&AR.
LI, &AR.
SE, &AR.
DT, DL, &AR.
TLI, &AR.
TTI);
3175 struct IndVarSimplifyLegacyPass :
public LoopPass {
3178 IndVarSimplifyLegacyPass() :
LoopPass(ID) {
3186 auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
3187 auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
3188 auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
3189 auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
3191 auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
3195 IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
3210 "Induction Variable Simplification",
false,
false)
3216 return new IndVarSimplifyLegacyPass();
Pass interface - Implemented by all 'passes'.
static cl::opt< ReplaceExitVal > ReplaceExitValue("replexitval", cl::Hidden, cl::init(OnlyCheapRepl), cl::desc("Choose the strategy to replace exit value in IndVarSimplify"), cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"), clEnumValN(OnlyCheapRepl, "cheap", "only replace exit value when the cost is cheap"), clEnumValN(NoHardUse, "noharduse", "only replace exit values when loop def likely dead"), clEnumValN(AlwaysRepl, "always", "always replace exit value whenever possible")))
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
A parsed version of the target data layout string in and methods for querying it. ...
bool hoistIVInc(Instruction *IncV, Instruction *InsertPos)
Utility for hoisting an IV increment.
Induction Variable Simplification
reference emplace_back(ArgTypes &&... Args)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
Value * CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS, const Twine &Name="")
static PHINode * getLoopPhiForCounter(Value *IncV, Loop *L)
Given an Value which is hoped to be part of an add recurance in the given loop, return the associated...
iterator_range< use_iterator > uses()
PreservedAnalyses run(Loop &L, LoopAnalysisManager &AM, LoopStandardAnalysisResults &AR, LPMUpdater &U)
void addIncoming(Value *V, BasicBlock *BB)
Add an incoming value to the end of the PHI list.
BlockT * getLoopLatch() const
If there is a single latch block for this loop, return it.
static PassRegistry * getPassRegistry()
getPassRegistry - Access the global registry object, which is automatically initialized at applicatio...
PreservedAnalyses getLoopPassPreservedAnalyses()
Returns the minimum set of Analyses that all loop passes must preserve.
MutableArrayRef< T > makeMutableArrayRef(T &OneElt)
Construct a MutableArrayRef from a single element.
This class represents lattice values for constants.
This header provides classes for managing a pipeline of passes over loops in LLVM IR...
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...
bool isRecursivelyLCSSAForm(DominatorTree &DT, const LoopInfo &LI) const
Return true if this Loop and all inner subloops are in LCSSA form.
bool isLCSSAForm(DominatorTree &DT) const
Return true if the Loop is in LCSSA form.
This class represents zero extension of integer types.
void push_back(const T &Elt)
This provides a very simple, boring adaptor for a begin and end iterator into a range type...
The main scalar evolution driver.
bool isZero() const
Return true if the expression is a constant zero.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
bool isHighCostExpansion(const SCEV *Expr, Loop *L, const Instruction *At=nullptr)
Return true for expressions that may incur non-trivial cost to evaluate at runtime.
0 1 0 0 True if ordered and less than
LLVMContext & getContext() const
All values hold a context through their type.
1 1 1 0 True if unordered or not equal
uint64_t getTypeSizeInBits(Type *Ty) const
Return the size in bits of the specified type, for which isSCEVable must return true.
void setDebugType(const char *s)
NodeT * findNearestCommonDominator(NodeT *A, NodeT *B) const
findNearestCommonDominator - Find nearest common dominator basic block for basic block A and B...
bool isLoopInvariant(const SCEV *S, const Loop *L)
Return true if the value of the given SCEV is unchanging in the specified loop.
bool all_of(R &&range, UnaryPredicate P)
Provide wrappers to std::all_of which take ranges instead of having to pass begin/end explicitly...
BasicBlock * getSuccessor(unsigned i) const
Value * CreateSExt(Value *V, Type *DestTy, const Twine &Name="")
STATISTIC(NumFunctions, "Total number of functions")
The adaptor from a function pass to a loop pass computes these analyses and makes them available to t...
static cl::opt< bool > UsePostIncrementRanges("indvars-post-increment-ranges", cl::Hidden, cl::desc("Use post increment control-dependent ranges in IndVarSimplify"), cl::init(true))
This class represents a sign extension of integer types.
static IntegerType * getInt64Ty(LLVMContext &C)
Value * getCondition() const
static bool mustExecuteUBIfPoisonOnPathTo(Instruction *Root, Instruction *OnPathTo, DominatorTree *DT)
Return true if undefined behavior would provable be executed on the path to OnPathTo if Root produced...
const Instruction * getTerminator() const LLVM_READONLY
Returns the terminator instruction if the block is well formed or null if the block is not well forme...
static ConstantRange makeAllowedICmpRegion(CmpInst::Predicate Pred, const ConstantRange &Other)
Produce the smallest range such that all values that may satisfy the given predicate with any value c...
This defines the Use class.
bool hasNoSignedWrap() const
static bool hasConcreteDef(Value *V)
Return true if the given value is concrete.
bool isReachableFromEntry(const Use &U) const
Provide an overload for a Use.
bool hasLoopInvariantOperands(const Instruction *I) const
Return true if all the operands of the specified instruction are loop invariant.
bool propagatesFullPoison(const Instruction *I)
Return true if this function can prove that I is guaranteed to yield full-poison (all bits poison) if...
static Value * genLoopLimit(PHINode *IndVar, BasicBlock *ExitingBB, const SCEV *ExitCount, bool UsePostInc, Loop *L, SCEVExpander &Rewriter, ScalarEvolution *SE)
Insert an IR expression which computes the value held by the IV IndVar (which must be an loop counter...
INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars", "Induction Variable Simplification", false, false) INITIALIZE_PASS_END(IndVarSimplifyLegacyPass
iterator begin()
Instruction iterator methods.
opStatus convertToInteger(MutableArrayRef< integerPart > Input, unsigned int Width, bool IsSigned, roundingMode RM, bool *IsExact) const
std::pair< iterator, bool > insert(const std::pair< KeyT, ValueT > &KV)
1 0 0 1 True if unordered or equal
bool match(Val *V, const Pattern &P)
Interface for visiting interesting IV users that are recognized but not simplified by this utility...
const Module * getModule() const
Return the module owning the function this basic block belongs to, or nullptr if the function does no...
#define INITIALIZE_PASS_DEPENDENCY(depName)
StringRef getName(ID id)
Return the LLVM name for an intrinsic, such as "llvm.ppc.altivec.lvx".
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
const DataLayout & getDataLayout() const
Get the data layout for the module's target platform.
int getBasicBlockIndex(const BasicBlock *BB) const
Return the first index of the specified basic block in the value list for this PHI.
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
bool isNonNegative() const
Determine if this APInt Value is non-negative (>= 0)
This is the base class for all instructions that perform data casts.
A Use represents the edge between a Value definition and its users.
static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal)
Convert APF to an integer, if possible.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
bool isIntegerTy() const
True if this is an instance of IntegerType.
0 1 0 1 True if ordered and less than or equal
This file implements a class to represent arbitrary precision integral constant values and operations...
BlockT * getHeader() const
Interval::succ_iterator succ_begin(Interval *I)
succ_begin/succ_end - define methods so that Intervals may be used just like BasicBlocks can with the...
Instruction::CastOps getOpcode() const
Return the opcode of this CastInst.
Type * getType() const
All values are typed, get the type of this value.
Value handle that is nullable, but tries to track the Value.
This node represents a polynomial recurrence on the trip count of the specified loop.
ConstantRange intersectWith(const ConstantRange &CR, PreferredRangeType Type=Smallest) const
Return the range that results from the intersection of this range with another range.
static bool isLoopExitTestBasedOn(Value *V, BasicBlock *ExitingBB)
Whether the current loop exit test is based on this value.
This instruction compares its operands according to the predicate given to the constructor.
static Instruction * getInsertPointForUses(Instruction *User, Value *Def, DominatorTree *DT, LoopInfo *LI)
Determine the insertion point for this user.
static cl::opt< bool > VerifyIndvars("verify-indvars", cl::Hidden, cl::desc("Verify the ScalarEvolution result after running indvars"))
bool DeleteDeadPHIs(BasicBlock *BB, const TargetLibraryInfo *TLI=nullptr)
Examine each PHI in the given block and delete it if it is dead.
const SCEV * getSizeOfExpr(Type *IntTy, Type *AllocTy)
Return an expression for sizeof AllocTy that is type IntTy.
const SCEV * getExitCount(const Loop *L, BasicBlock *ExitingBlock, ExitCountKind Kind=Exact)
Return the number of times the backedge executes before the given exit would be taken; if not exactly...
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void SetCurrentDebugLocation(DebugLoc L)
Set location information used by debugging information.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
bool replaceAllDbgUsesWith(Instruction &From, Value &To, Instruction &DomPoint, DominatorTree &DT)
Point debug users of From to To or salvage them.
Value * CreateZExt(Value *V, Type *DestTy, const Twine &Name="")
const SCEV * getStepRecurrence(ScalarEvolution &SE) const
Constructs and returns the recurrence indicating how much this expression steps by.
void takeName(Value *V)
Transfer the name from V to this value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
static BinaryOperator * CreateAdd(Value *S1, Value *S2, const Twine &Name, Instruction *InsertBefore, Value *FlagsOp)
void SetInsertPoint(BasicBlock *TheBB)
This specifies that created instructions should be appended to the end of the specified block...
Value * getOperand(unsigned i) const
void initializeIndVarSimplifyLegacyPassPass(PassRegistry &)
iterator find(const_arg_type_t< KeyT > Val)
void clearInsertPoint()
Clear the current insertion point.
void clear()
Erase the contents of the InsertedExpressions map so that users trying to expand the same expression ...
const SCEV * getCouldNotCompute()
initializer< Ty > init(const Ty &Val)
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
A set of analyses that are preserved following a run of a transformation pass.
const SCEV * getOne(Type *Ty)
Return a SCEV for the constant 1 of a specific type.
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
const_iterator getFirstInsertionPt() const
Returns an iterator to the first instruction in this block that is suitable for inserting a non-PHI i...
void setDebugLoc(DebugLoc Loc)
Set the debug location information for this instruction.
LLVM Basic Block Representation.
The instances of the Type class are immutable: once they are created, they are never changed...
void setInsertPoint(Instruction *IP)
Set the current insertion point.
Conditional or Unconditional Branch instruction.
static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl< Value *> &Visited, unsigned Depth)
Recursive helper for hasConcreteDef().
static GCRegistry::Add< CoreCLRGC > E("coreclr", "CoreCLR-compatible GC")
ValuesClass values(OptsTy... Options)
Helper to build a ValuesClass by forwarding a variable number of arguments as an initializer list to ...
Value * getIncomingValueForBlock(const BasicBlock *BB) const
SmallSet - This maintains a set of unique values, optimizing for the case when the set is small (less...
This file contains the declarations for the subclasses of Constant, which represent the different fla...
bool isPointerTy() const
True if this is an instance of PointerType.
const Instruction & front() const
ConstantFP - Floating Point Values [float, double].
static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE, const TargetTransformInfo *TTI)
Update information about the induction variable that is extended by this sign or zero extend operatio...
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
bool mayHaveSideEffects() const
Return true if the instruction may have side effects.
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.
bool mayThrow() const
Return true if this instruction may throw an exception.
bool mustTriggerUB(const Instruction *I, const SmallSet< const Value *, 16 > &KnownPoison)
Return true if the given instruction must trigger undefined behavior.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
Represent the analysis usage information of a pass.
This file declares a class to represent arbitrary precision floating point values and provide a varie...
bool any_of(R &&range, UnaryPredicate P)
Provide wrappers to std::any_of which take ranges instead of having to pass begin/end explicitly...
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
Utility class for integer operators which may exhibit overflow - Add, Sub, Mul, and Shl...
Value * expandCodeFor(const SCEV *SH, Type *Ty, Instruction *I)
Insert code to directly compute the specified SCEV expression into the program.
bool isAffine() const
Return true if this represents an expression A + B*x where A and B are loop invariant values...
self_iterator getIterator()
const SCEV * getStart() const
Class to represent integer types.
std::pair< NoneType, bool > insert(const T &V)
insert - Insert an element into the set if it isn't already there.
auto remove_if(R &&Range, UnaryPredicate P) -> decltype(adl_begin(Range))
Provide wrappers to std::remove_if which take ranges instead of having to pass begin/end explicitly...
bool RecursivelyDeleteTriviallyDeadInstructions(Value *V, const TargetLibraryInfo *TLI=nullptr, MemorySSAUpdater *MSSAU=nullptr)
If the specified value is a trivially dead instruction, delete it.
BlockT * getExitBlock() const
If getExitBlocks would return exactly one block, return that block.
void getExitingBlocks(SmallVectorImpl< BlockT *> &ExitingBlocks) const
Return all blocks inside the loop that have successors outside of the loop.
const SCEV * getUMinFromMismatchedTypes(const SCEV *LHS, const SCEV *RHS)
Promote the operands to the wider of the types using zero-extension, and then perform a umin operatio...
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
iterator erase(const_iterator CI)
static PreservedAnalyses all()
Construct a special preserved set that preserves all passes.
static unsigned getIncomingValueNumForOperand(unsigned i)
Value * getIncomingValue(unsigned i) const
Return incoming value number x.
1 1 0 1 True if unordered, less than, or equal
INITIALIZE_PASS_END(RegBankSelect, DEBUG_TYPE, "Assign register bank of generic virtual registers", false, false) RegBankSelect
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
Value * CreateTrunc(Value *V, Type *DestTy, const Twine &Name="")
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
TargetTransformInfo & TTI
void sort(IteratorTy Start, IteratorTy End)
const APFloat & getValueAPF() const
0 0 1 0 True if ordered and greater than
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...
bool contains(const LoopT *L) const
Return true if the specified loop is contained within in this loop.
Iterator for intrusive lists based on ilist_node.
unsigned getNumOperands() const
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
Type * getType() const
Return the LLVM type of this SCEV expression.
constexpr bool isInt< 32 >(int64_t x)
static cl::opt< bool > LoopPredication("indvars-predicate-loops", cl::Hidden, cl::init(true), cl::desc("Predicate conditions in read only loops"))
1 1 0 0 True if unordered or less than
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
bool dominates(const Instruction *Def, const Use &U) const
Return true if Def dominates a use in User.
Module.h This file contains the declarations for the Module class.
Instruction * user_back()
Specialize the methods defined in Value, as we know that an instruction can only be used by other ins...
Provides information about what library functions are available for the current target.
This class represents a range of values.
bool isLegalInteger(uint64_t Width) const
Returns true if the specified type is known to be a native integer type supported by the CPU...
static PHINode * FindLoopCounter(Loop *L, BasicBlock *ExitingBB, const SCEV *BECount, ScalarEvolution *SE, DominatorTree *DT)
Search the loop header for a loop counter (anadd rec w/step of one) suitable for use by LFTR...
LLVM_NODISCARD T pop_back_val()
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
bool isConditional() const
static PHINode * Create(Type *Ty, unsigned NumReservedValues, const Twine &NameStr="", Instruction *InsertBefore=nullptr)
Constructors - NumReservedValues is a hint for the number of incoming edges that this phi node will h...
void setPreservesCFG()
This function should be called by the pass, iff they do not:
unsigned getNumIncomingValues() const
Return the number of incoming edges.
static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI)
This IV user cannot be widened.
OverflowingBinaryOp_match< LHS, RHS, Instruction::Add, OverflowingBinaryOperator::NoSignedWrap > m_NSWAdd(const LHS &L, const RHS &R)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
void swap(llvm::BitVector &LHS, llvm::BitVector &RHS)
Implement std::swap in terms of BitVector swap.
const Module * getModule() const
Return the module owning the function this instruction belongs to or nullptr it the function does not...
Class for arbitrary precision integers.
static BinaryOperator * Create(BinaryOps Op, Value *S1, Value *S2, const Twine &Name=Twine(), Instruction *InsertBefore=nullptr)
Construct a binary instruction, given the opcode and the two operands.
iterator_range< user_iterator > users()
bool hasNoSignedWrap() const
Test whether this operation is known to never undergo signed overflow, aka the nsw property...
This class uses information about analyze scalars to rewrite expressions in canonical form...
Represents analyses that only rely on functions' control flow.
static const SCEV * getMaxBackedgeTakenCount(ScalarEvolution &SE, DominatorTree &DT, Loop *L)
Return a symbolic upper bound for the backedge taken count of the loop.
#define clEnumValN(ENUMVAL, FLAGNAME, DESC)
LoopT * getParentLoop() const
Virtual Register Rewriter
Predicate getPredicate() const
Return the predicate for this instruction.
bool isLoopSimplifyForm() const
Return true if the Loop is in the form that the LoopSimplify form transforms loops to...
This class represents an analyzed expression in the program.
static IntegerType * getInt32Ty(LLVMContext &C)
bool hasNoUnsignedWrap() const
LLVM_NODISCARD bool empty() const
Represents a single loop in the control flow graph.
ArrayRef< BlockT * > getBlocks() const
Get a list of the basic blocks which make up this loop.
StringRef getName() const
Return a constant reference to the value's name.
BasicBlock * getIncomingBlock(unsigned i) const
Return incoming basic block number i.
const Function * getParent() const
Return the enclosing method, or null if none.
user_iterator_impl< User > user_iterator
bool mayReadFromMemory() const
Return true if this instruction may read memory.
void getLoopAnalysisUsage(AnalysisUsage &AU)
Helper to consistently add the set of standard passes to a loop pass's AnalysisUsage.
0 1 1 0 True if ordered and operands are unequal
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
static bool isLoopCounter(PHINode *Phi, Loop *L, ScalarEvolution *SE)
Return true if the given phi is a "counter" in L.
iterator_range< const_phi_iterator > phis() const
Returns a range that iterates over the phis in the basic block.
bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead, SCEVExpander &Rewriter, IVVisitor *V=nullptr)
simplifyUsersOfIV - Simplify instructions that use this induction variable by using ScalarEvolution t...
const SCEV * getTruncateOrZeroExtend(const SCEV *V, Type *Ty, unsigned Depth=0)
Return a SCEV corresponding to a conversion of the input value to the specified type.
1 0 1 0 True if unordered or greater than
void setCondition(Value *V)
unsigned replaceCongruentIVs(Loop *L, const DominatorTree *DT, SmallVectorImpl< WeakTrackingVH > &DeadInsts, const TargetTransformInfo *TTI=nullptr)
replace congruent phis with their most canonical representative.
This class represents a cast from signed integer to floating point.
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
user_iterator user_begin()
bool isOne() const
Return true if the expression is a constant one.
0 0 0 1 True if ordered and equal
Module * getParent()
Get the module that this global value is contained inside of...
bool isInstructionTriviallyDead(Instruction *I, const TargetLibraryInfo *TLI=nullptr)
Return true if the result produced by the instruction is not used, and the instruction has no side ef...
LLVM Value Representation.
1 0 1 1 True if unordered, greater than, or equal
const SCEV * getSCEV(Value *V)
Return a SCEV expression for the full generality of the specified expression.
A constant which provides an upper bound on the exact trip count.
const SCEV * getTruncateExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
#define LLVM_FALLTHROUGH
LLVM_FALLTHROUGH - Mark fallthrough cases in switch statements.
static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond)
Return true if this IV has any uses other than the (soon to be rewritten) loop exit test...
void moveBefore(Instruction *MovePos)
Unlink this instruction from its current basic block and insert it into the basic block that MovePos ...
void disableCanonicalMode()
Disable the behavior of expanding expressions in canonical form rather than in a more literal form...
bool isEHPad() const
Return true if the instruction is a variety of EH-block.
void getUniqueExitBlocks(SmallVectorImpl< BlockT *> &ExitBlocks) const
Return all unique successor blocks of this loop.
bool hasOneUse() const
Return true if there is exactly one user of this value.
A container for analyses that lazily runs them and caches their results.
This header defines various interfaces for pass management in LLVM.
void setIncomingValue(unsigned i, Value *V)
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...
iterator_range< block_iterator > blocks() const
static cl::opt< bool > DisableLFTR("disable-lftr", cl::Hidden, cl::init(false), cl::desc("Disable Linear Function Test Replace optimization"))
0 0 1 1 True if ordered and greater than or equal
static bool needsLFTR(Loop *L, BasicBlock *ExitingBB)
linearFunctionTestReplace policy.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
Pass * createIndVarSimplifyPass()
const BasicBlock * getParent() const
This class represents a constant integer value.
CmpClass_match< LHS, RHS, ICmpInst, ICmpInst::Predicate > m_ICmp(ICmpInst::Predicate &Pred, const LHS &L, const RHS &R)
bool hasNoUnsignedWrap() const
Test whether this operation is known to never undergo unsigned overflow, aka the nuw property...
bool makeLoopInvariant(Value *V, bool &Changed, Instruction *InsertPt=nullptr, MemorySSAUpdater *MSSAU=nullptr) const
If the given value is an instruction inside of the loop and it can be hoisted, do so to make it trivi...