33 #define DEBUG_TYPE "indvars" 35 STATISTIC(NumElimIdentity,
"Number of IV identities eliminated");
36 STATISTIC(NumElimOperand,
"Number of IV operands folded into a use");
37 STATISTIC(NumFoldedUser,
"Number of IV users folded into a constant");
38 STATISTIC(NumElimRem ,
"Number of IV remainder operations eliminated");
41 "Number of IV signed division operations converted to unsigned division");
44 "Number of IV signed remainder operations converted to unsigned remainder");
45 STATISTIC(NumElimCmp ,
"Number of IV comparisons eliminated");
52 class SimplifyIndvar {
66 : L(Loop), LI(LI), SE(SE), DT(DT), Rewriter(Rewriter), DeadInsts(Dead),
68 assert(LI &&
"IV simplification requires LoopInfo");
71 bool hasChanged()
const {
return Changed; }
81 bool replaceIVUserWithLoopInvariant(
Instruction *UseInst);
87 bool makeIVComparisonInvariant(
ICmpInst *ICmp,
Value *IVOperand);
109 Value *IVSrc =
nullptr;
110 const unsigned OperIdx = 0;
111 const SCEV *FoldedExpr =
nullptr;
112 bool MustDropExactFlag =
false;
116 case Instruction::UDiv:
117 case Instruction::LShr:
120 if (IVOperand != UseInst->
getOperand(OperIdx) ||
126 if (!isa<BinaryOperator>(IVOperand)
127 || !isa<ConstantInt>(IVOperand->
getOperand(1)))
132 assert(SE->isSCEVable(IVSrc->
getType()) &&
"Expect SCEVable IV operand");
135 if (UseInst->
getOpcode() == Instruction::LShr) {
144 FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
148 SE->getSCEV(IVSrc) != SE->getMulExpr(FoldedExpr, SE->getSCEV(D)))
149 MustDropExactFlag =
true;
152 if (!SE->isSCEVable(UseInst->
getType()))
156 if (SE->getSCEV(UseInst) != FoldedExpr)
159 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated IV operand: " << *IVOperand
160 <<
" -> " << *UseInst <<
'\n');
163 assert(SE->getSCEV(UseInst) == FoldedExpr &&
"bad SCEV with folded oper");
165 if (MustDropExactFlag)
171 DeadInsts.emplace_back(IVOperand);
175 bool SimplifyIndvar::makeIVComparisonInvariant(
ICmpInst *ICmp,
177 unsigned IVOperIdx = 0;
189 const SCEV *S = SE->getSCEVAtScope(ICmp->
getOperand(IVOperIdx), ICmpLoop);
190 const SCEV *
X = SE->getSCEVAtScope(ICmp->
getOperand(1 - IVOperIdx), ICmpLoop);
193 const SCEV *InvariantLHS, *InvariantRHS;
198 if (!SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
199 InvariantLHS, InvariantRHS))
207 CheapExpansions[S] = ICmp->
getOperand(IVOperIdx);
208 CheapExpansions[
X] = ICmp->
getOperand(1 - IVOperIdx);
212 if (
auto *BB = L->getLoopPredecessor()) {
213 const int Idx = PN->getBasicBlockIndex(BB);
215 Value *Incoming = PN->getIncomingValue(Idx);
216 const SCEV *IncomingS = SE->getSCEV(Incoming);
217 CheapExpansions[IncomingS] = Incoming;
220 Value *NewLHS = CheapExpansions[InvariantLHS];
221 Value *NewRHS = CheapExpansions[InvariantRHS];
224 if (
auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
225 NewLHS = ConstLHS->getValue();
227 if (
auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
228 NewRHS = ConstRHS->getValue();
230 if (!NewLHS || !NewRHS)
236 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified comparison: " << *ICmp <<
'\n');
245 void SimplifyIndvar::eliminateIVComparison(
ICmpInst *ICmp,
Value *IVOperand) {
246 unsigned IVOperIdx = 0;
259 const SCEV *S = SE->getSCEVAtScope(ICmp->
getOperand(IVOperIdx), ICmpLoop);
260 const SCEV *X = SE->getSCEVAtScope(ICmp->
getOperand(1 - IVOperIdx), ICmpLoop);
264 if (SE->isKnownPredicate(Pred, S, X)) {
266 DeadInsts.emplace_back(ICmp);
267 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated comparison: " << *ICmp <<
'\n');
270 DeadInsts.emplace_back(ICmp);
271 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated comparison: " << *ICmp <<
'\n');
272 }
else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
275 SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
282 LLVM_DEBUG(
dbgs() <<
"INDVARS: Turn to unsigned comparison: " << *ICmp
299 N = SE->getSCEVAtScope(
N, L);
300 D = SE->getSCEVAtScope(D, L);
303 if (SE->isKnownNonNegative(
N) && SE->isKnownNonNegative(D)) {
306 SDiv->
getName() +
".udiv", SDiv);
309 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified sdiv: " << *SDiv <<
'\n');
312 DeadInsts.push_back(SDiv);
323 Rem->
getName() +
".urem", Rem);
325 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified srem: " << *Rem <<
'\n');
328 DeadInsts.emplace_back(Rem);
332 void SimplifyIndvar::replaceRemWithNumerator(
BinaryOperator *Rem) {
334 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified rem: " << *Rem <<
'\n');
337 DeadInsts.emplace_back(Rem);
341 void SimplifyIndvar::replaceRemWithNumeratorOrZero(
BinaryOperator *Rem) {
348 LLVM_DEBUG(
dbgs() <<
"INDVARS: Simplified rem: " << *Rem <<
'\n');
351 DeadInsts.emplace_back(Rem);
363 bool UsedAsNumerator = IVOperand == NValue;
364 if (!UsedAsNumerator && !IsSigned)
367 const SCEV *
N = SE->getSCEV(NValue);
371 N = SE->getSCEVAtScope(N, ICmpLoop);
373 bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
376 if (!IsNumeratorNonNegative)
379 const SCEV *D = SE->getSCEV(DValue);
380 D = SE->getSCEVAtScope(D, ICmpLoop);
382 if (UsedAsNumerator) {
384 if (SE->isKnownPredicate(
LT, N, D)) {
385 replaceRemWithNumerator(Rem);
390 const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(
T));
391 if (SE->isKnownPredicate(
LT, NLessOne, D)) {
392 replaceRemWithNumeratorOrZero(Rem);
399 if (!IsSigned || !SE->isKnownNonNegative(D))
402 replaceSRemWithURem(Rem);
415 case Instruction::Sub:
418 case Instruction::Mul:
428 auto *NarrowTy = cast<IntegerType>(LHS->
getType());
437 (SE->*
Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
460 for (
auto *U : WO->
users()) {
461 if (
auto *EVI = dyn_cast<ExtractValueInst>(U)) {
462 if (EVI->getIndices()[0] == 1)
465 assert(EVI->getIndices()[0] == 0 &&
"Only two possibilities!");
466 EVI->replaceAllUsesWith(NewResult);
472 for (
auto *EVI : ToDelete)
473 EVI->eraseFromParent();
495 DeadInsts.emplace_back(SI);
500 bool SimplifyIndvar::eliminateTrunc(
TruncInst *TI) {
519 const SCEV *IVSCEV = SE->getSCEV(IV);
520 const SCEV *TISCEV = SE->getSCEV(TI);
524 bool DoesSExtCollapse =
false;
525 bool DoesZExtCollapse =
false;
526 if (IVSCEV == SE->getSignExtendExpr(TISCEV, IVTy))
527 DoesSExtCollapse =
true;
528 if (IVSCEV == SE->getZeroExtendExpr(TISCEV, IVTy))
529 DoesZExtCollapse =
true;
533 if (!DoesSExtCollapse && !DoesZExtCollapse)
539 for (
auto *U : TI->
users()) {
541 if (isa<Instruction>(U) &&
542 !DT->isReachableFromEntry(cast<Instruction>(U)->
getParent()))
545 if (!ICI)
return false;
551 if (ICI->
isSigned() && !DoesSExtCollapse)
559 auto CanUseZExt = [&](
ICmpInst *ICI) {
561 if (ICI->isUnsigned())
564 if (!DoesZExtCollapse)
567 if (ICI->isEquality())
573 const SCEV *SCEVOP1 = SE->getSCEV(ICI->getOperand(0));
574 const SCEV *SCEVOP2 = SE->getSCEV(ICI->getOperand(1));
575 return SE->isKnownNonNegative(SCEVOP1) && SE->isKnownNonNegative(SCEVOP2);
578 for (
auto *ICI : ICmpUsers) {
580 auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
590 if (CanUseZExt(ICI)) {
591 assert(DoesZExtCollapse &&
"Unprofitable zext?");
592 Ext =
new ZExtInst(Op1, IVTy,
"zext", ICI);
595 assert(DoesSExtCollapse &&
"Unprofitable sext?");
596 Ext =
new SExtInst(Op1, IVTy,
"sext", ICI);
603 ICI->replaceAllUsesWith(NewICI);
604 DeadInsts.emplace_back(ICI);
609 DeadInsts.emplace_back(TI);
616 bool SimplifyIndvar::eliminateIVUser(
Instruction *UseInst,
618 if (
ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
619 eliminateIVComparison(ICmp, IVOperand);
623 bool IsSRem = Bin->getOpcode() == Instruction::SRem;
624 if (IsSRem || Bin->getOpcode() == Instruction::URem) {
625 simplifyIVRemainder(Bin, IVOperand, IsSRem);
629 if (Bin->getOpcode() == Instruction::SDiv)
630 return eliminateSDiv(Bin);
633 if (
auto *WO = dyn_cast<WithOverflowInst>(UseInst))
634 if (eliminateOverflowIntrinsic(WO))
637 if (
auto *SI = dyn_cast<SaturatingInst>(UseInst))
638 if (eliminateSaturatingIntrinsic(SI))
641 if (
auto *TI = dyn_cast<TruncInst>(UseInst))
642 if (eliminateTrunc(TI))
645 if (eliminateIdentitySCEV(UseInst, IVOperand))
653 return BB->getTerminator();
659 bool SimplifyIndvar::replaceIVUserWithLoopInvariant(
Instruction *
I) {
660 if (!SE->isSCEVable(I->
getType()))
664 const SCEV *S = SE->getSCEV(I);
666 if (!SE->isLoopInvariant(S, L))
670 if (
Rewriter.isHighCostExpansion(S, L, I))
678 <<
" with loop invariant: " << *S <<
'\n');
681 DeadInsts.emplace_back(I);
686 bool SimplifyIndvar::eliminateIdentitySCEV(
Instruction *UseInst,
688 if (!SE->isSCEVable(UseInst->
getType()) ||
690 (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
709 if (isa<PHINode>(UseInst))
712 if (!DT || !DT->dominates(IVOperand, UseInst))
715 if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
718 LLVM_DEBUG(
dbgs() <<
"INDVARS: Eliminated identity: " << *UseInst <<
'\n');
723 DeadInsts.emplace_back(UseInst);
729 bool SimplifyIndvar::strengthenOverflowingOperation(
BinaryOperator *BO,
742 bool Changed =
false;
768 if (BO->
getOpcode() == Instruction::Shl) {
769 bool Changed =
false;
770 ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
771 for (
auto *U : BO->
users()) {
794 SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
812 if (!Simplified.
insert(UI).second)
815 SimpleIVUsers.push_back(std::make_pair(UI, Def));
853 if (!SE->isSCEVable(CurrIV->
getType()))
867 while (!SimpleIVUsers.
empty()) {
868 std::pair<Instruction*, Instruction*> UseOper =
877 DeadInsts.emplace_back(UseInst);
882 if (UseInst == CurrIV)
continue;
886 if (replaceIVUserWithLoopInvariant(UseInst))
890 for (
unsigned N = 0; IVOperand; ++
N) {
891 assert(N <= Simplified.
size() &&
"runaway iteration");
893 Value *NewOper = foldIVUser(UseInst, IVOperand);
901 if (eliminateIVUser(UseInst, IVOperand)) {
902 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
907 if ((isa<OverflowingBinaryOperator>(BO) &&
908 strengthenOverflowingOperation(BO, IVOperand)) ||
909 (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
912 pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
922 pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
938 SIV.simplifyUsers(CurrIV, V);
939 return SIV.hasChanged();
950 bool Changed =
false;
static unsigned getBitWidth(Type *Ty, const DataLayout &DL)
Returns the bitwidth of the given scalar or pointer type.
SymbolTableList< Instruction >::iterator eraseFromParent()
This method unlinks 'this' from the containing basic block and deletes it.
static ConstantInt * getFalse(LLVMContext &Context)
class_match< Value > m_Value()
Match an arbitrary value and ignore it.
static GCMetadataPrinterRegistry::Add< ErlangGCPrinter > X("erlang", "erlang-compatible garbage collector")
This class represents lattice values for constants.
BinaryOps getOpcode() const
Represents an op.with.overflow intrinsic.
This class represents zero extension of integer types.
void push_back(const T &Elt)
The main scalar evolution driver.
BlockT * getLoopPreheader() const
If there is a preheader for this loop, return it.
BinaryOp_match< LHS, RHS, Instruction::AShr > m_AShr(const LHS &L, const RHS &R)
static SelectInst * Create(Value *C, Value *S1, Value *S2, const Twine &NameStr="", Instruction *InsertBefore=nullptr, Instruction *MDFrom=nullptr)
LLVMContext & getContext() const
All values hold a context through their type.
STATISTIC(NumFunctions, "Total number of functions")
This class represents a sign extension of integer types.
bool hasNoSignedWrap() const
Determine whether the no signed wrap flag is set.
iterator begin()
Instruction iterator methods.
bool match(Val *V, const Pattern &P)
Interface for visiting interesting IV users that are recognized but not simplified by this utility...
This class represents the LLVM 'select' instruction.
Predicate getInversePredicate() const
For example, EQ -> NE, UGT -> ULE, SLT -> SGE, OEQ -> UNE, UGT -> OLE, OLT -> UGE, etc.
const Loop * getLoop() const
LoopT * getLoopFor(const BlockT *BB) const
Return the inner most loop that BB lives in.
This is the base class for all instructions that perform data casts.
This class consists of common code factored out of the SmallVector class to reduce code duplication b...
void dropPoisonGeneratingFlags()
Drops flags that may cause this instruction to evaluate to poison despite having non-poison inputs...
BlockT * getHeader() const
void setIsExact(bool b=true)
Set or clear the exact flag on this instruction, which must be an operator which supports this flag...
Type * getType() const
All values are typed, get the type of this value.
This node represents a polynomial recurrence on the trip count of the specified loop.
bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT, LoopInfo *LI, SmallVectorImpl< WeakTrackingVH > &Dead)
SimplifyLoopIVs - Simplify users of induction variables within this loop.
const APInt & getValue() const
Return the constant as an APInt value reference.
unsigned getOpcode() const
Returns a member of one of the enums like Instruction::Add.
void replaceAllUsesWith(Value *V)
Change all uses of this to point to a new Value.
Concrete subclass of DominatorTreeBase that is used to compute a normal dominator tree...
APInt getUnsignedMin() const
Return the smallest unsigned value contained in the ConstantRange.
This class represents a truncation of integer types.
Value * getOperand(unsigned i) const
BinaryOp_match< LHS, RHS, Instruction::LShr > m_LShr(const LHS &L, const RHS &R)
uint64_t getZExtValue() const
Return the constant as a 64-bit unsigned integer value after it has been zero extended as appropriate...
static GCRegistry::Add< OcamlGC > B("ocaml", "ocaml 3.10-compatible GC")
apint_match m_APInt(const APInt *&Res)
Match a ConstantInt or splatted ConstantVector, binding the specified pointer to the contained APInt...
The instances of the Type class are immutable: once they are created, they are never changed...
PowerPC Reduce CR logical Operation
bool isSigned() const
Whether the intrinsic is signed or unsigned.
std::pair< iterator, bool > insert(PtrType Ptr)
Inserts Ptr if and only if there is no element in the container equal to Ptr.
const SCEV * getAddExpr(SmallVectorImpl< const SCEV *> &Ops, SCEV::NoWrapFlags Flags=SCEV::FlagAnyWrap, unsigned Depth=0)
Get a canonical add expression, or something simpler if possible.
static APInt getOneBitSet(unsigned numBits, unsigned BitNo)
Return an APInt with exactly one bit set in the result.
specificval_ty m_Specific(const Value *V)
Match if we have a specific specified value.
BinaryOp_match< LHS, RHS, Instruction::Shl > m_Shl(const LHS &L, const RHS &R)
This instruction compares its operands according to the predicate given to the constructor.
Predicate
This enumeration lists the possible predicates for CmpInst subclasses.
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 bool willNotOverflow(ScalarEvolution *SE, Instruction::BinaryOps BinOp, bool Signed, const SCEV *LHS, const SCEV *RHS)
static UndefValue * get(Type *T)
Static factory methods - Return an 'undef' object of the specified type.
bool isExact() const
Determine whether the exact flag is set.
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.
#define llvm_unreachable(msg)
Marks that the current location is not supposed to be reachable.
bool isLoopInvariant(const Value *V) const
Return true if the specified value is loop invariant.
static IntegerType * get(LLVMContext &C, unsigned NumBits)
This static method is the primary way of constructing an IntegerType.
void setHasNoSignedWrap(bool b=true)
Set or clear the nsw flag on this instruction, which must be an operator which supports this flag...
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.
SmallPtrSet - This class implements a set which is optimized for holding SmallSize or less elements...
This is the shared class of boolean and integer constants.
Type * getType() const
Return the LLVM type of this SCEV expression.
This is a 'vector' (really, a variable-sized array), optimized for the case when the array is small...
Represents a saturating add/sub intrinsic.
static Instruction * GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint)
This class represents a range of values.
LLVM_NODISCARD T pop_back_val()
static GCRegistry::Add< StatepointGC > D("statepoint-example", "an example strategy for statepoint")
static Constant * get(Type *Ty, uint64_t V, bool isSigned=false)
If Ty is a vector type, return a Constant with a splat of the given value.
Predicate getSignedPredicate() const
For example, EQ->EQ, SLE->SLE, UGT->SGT, etc.
bool uge(const APInt &RHS) const
Unsigned greater or equal comparison.
static ConstantInt * getTrue(LLVMContext &Context)
void setPredicate(Predicate P)
Set the predicate for this instruction to the specified value.
void setOperand(unsigned i, Value *Val)
raw_ostream & dbgs()
dbgs() - This returns a reference to a raw_ostream for debugging messages.
static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE)
Return true if this instruction generates a simple SCEV expression in terms of that IV...
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()
This class uses information about analyze scalars to rewrite expressions in canonical form...
const DataLayout & getDataLayout() const
Return the DataLayout associated with the module this SCEV instance is operating on.
Virtual Register Rewriter
Predicate getPredicate() const
Return the predicate for this instruction.
Instruction::BinaryOps getBinaryOp() const
Returns the binary operation underlying the intrinsic.
This class represents an analyzed expression in the program.
LLVM_NODISCARD bool empty() const
virtual void visitCast(CastInst *Cast)=0
Represents a single loop in the control flow graph.
StringRef getName() const
Return a constant reference to the value's name.
LLVM_NODISCARD std::enable_if<!is_simple_type< Y >::value, typename cast_retty< X, const Y >::ret_type >::type dyn_cast(const Y &Val)
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...
bool hasNoUnsignedWrap() const
Determine whether the no unsigned wrap flag is set.
void setHasNoUnsignedWrap(bool b=true)
Set or clear the nuw flag on this instruction, which must be an operator which supports this flag...
assert(ImpDefSCC.getReg()==AMDGPU::SCC &&ImpDefSCC.isDef())
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.
bool isSCEVable(Type *Ty) const
Test if values of the given type are analyzable within the SCEV framework.
static const Function * getParent(const Value *V)
Predicate getSwappedPredicate() const
For example, EQ->EQ, SLE->SGE, ULT->UGT, OEQ->OEQ, ULE->UGE, OLT->OGT, etc.
NoWrapFlags
NoWrapFlags are bitfield indices into SubclassData.
Predicate getUnsignedPredicate() const
For example, EQ->EQ, SLE->ULE, UGT->UGT, etc.
const SCEV * getZeroExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const SCEV * getSignExtendExpr(const SCEV *Op, Type *Ty, unsigned Depth=0)
const BasicBlock * getParent() const
static void pushIVUsers(Instruction *Def, Loop *L, SmallPtrSet< Instruction *, 16 > &Simplified, SmallVectorImpl< std::pair< Instruction *, Instruction *> > &SimpleIVUsers)
Add all uses of Def to the current IV's worklist.
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...