1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 //
10 // This file implements induction variable simplification. It does
11 // not define any actual pass or policy, but provides a single function to
12 // simplify a loop's induction variables based on ScalarEvolution.
13 //
14 //===----------------------------------------------------------------------===//
15 
16 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
17 #include "llvm/ADT/STLExtras.h"
18 #include "llvm/ADT/SmallVector.h"
19 #include "llvm/ADT/Statistic.h"
20 #include "llvm/Analysis/LoopInfo.h"
21 #include "llvm/Analysis/LoopPass.h"
22 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
23 #include "llvm/IR/DataLayout.h"
24 #include "llvm/IR/Dominators.h"
25 #include "llvm/IR/IRBuilder.h"
26 #include "llvm/IR/Instructions.h"
27 #include "llvm/IR/IntrinsicInst.h"
28 #include "llvm/IR/PatternMatch.h"
29 #include "llvm/Support/Debug.h"
30 #include "llvm/Support/raw_ostream.h"
31 
32 using namespace llvm;
33 
34 #define DEBUG_TYPE "indvars"
35 
36 STATISTIC(NumElimIdentity, "Number of IV identities eliminated");
37 STATISTIC(NumElimOperand,  "Number of IV operands folded into a use");
38 STATISTIC(NumElimRem     , "Number of IV remainder operations eliminated");
39 STATISTIC(
40     NumSimplifiedSDiv,
41     "Number of IV signed division operations converted to unsigned division");
42 STATISTIC(
43     NumSimplifiedSRem,
44     "Number of IV signed remainder operations converted to unsigned remainder");
45 STATISTIC(NumElimCmp     , "Number of IV comparisons eliminated");
46 
47 namespace {
48   /// This is a utility for simplifying induction variables
49   /// based on ScalarEvolution. It is the primary instrument of the
50   /// IndvarSimplify pass, but it may also be directly invoked to cleanup after
51   /// other loop passes that preserve SCEV.
52   class SimplifyIndvar {
53     Loop             *L;
54     LoopInfo         *LI;
55     ScalarEvolution  *SE;
56     DominatorTree    *DT;
57 
58     SmallVectorImpl<WeakTrackingVH> &DeadInsts;
59 
60     bool Changed;
61 
62   public:
63     SimplifyIndvar(Loop *Loop, ScalarEvolution *SE, DominatorTree *DT,
64                    LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead)
65         : L(Loop), LI(LI), SE(SE), DT(DT), DeadInsts(Dead), Changed(false) {
66       assert(LI && "IV simplification requires LoopInfo");
67     }
68 
69     bool hasChanged() const { return Changed; }
70 
71     /// Iteratively perform simplification on a worklist of users of the
72     /// specified induction variable. This is the top-level driver that applies
73     /// all simplifications to users of an IV.
74     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
75 
76     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
77 
78     bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
79 
80     bool eliminateOverflowIntrinsic(CallInst *CI);
81     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
82     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
83     void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
84                              bool IsSigned);
85     void replaceRemWithNumerator(BinaryOperator *Rem);
86     void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
87     void replaceSRemWithURem(BinaryOperator *Rem);
88     bool eliminateSDiv(BinaryOperator *SDiv);
89     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
90     bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
91   };
92 }
93 
94 /// Fold an IV operand into its use.  This removes increments of an
95 /// aligned IV when used by a instruction that ignores the low bits.
96 ///
97 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
98 ///
99 /// Return the operand of IVOperand for this induction variable if IVOperand can
100 /// be folded (in case more folding opportunities have been exposed).
101 /// Otherwise return null.
102 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
103   Value *IVSrc = nullptr;
104   unsigned OperIdx = 0;
105   const SCEV *FoldedExpr = nullptr;
106   switch (UseInst->getOpcode()) {
107   default:
108     return nullptr;
109   case Instruction::UDiv:
110   case Instruction::LShr:
111     // We're only interested in the case where we know something about
112     // the numerator and have a constant denominator.
113     if (IVOperand != UseInst->getOperand(OperIdx) ||
114         !isa<ConstantInt>(UseInst->getOperand(1)))
115       return nullptr;
116 
117     // Attempt to fold a binary operator with constant operand.
118     // e.g. ((I + 1) >> 2) => I >> 2
119     if (!isa<BinaryOperator>(IVOperand)
120         || !isa<ConstantInt>(IVOperand->getOperand(1)))
121       return nullptr;
122 
123     IVSrc = IVOperand->getOperand(0);
124     // IVSrc must be the (SCEVable) IV, since the other operand is const.
125     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
126 
127     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
128     if (UseInst->getOpcode() == Instruction::LShr) {
129       // Get a constant for the divisor. See createSCEV.
130       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
131       if (D->getValue().uge(BitWidth))
132         return nullptr;
133 
134       D = ConstantInt::get(UseInst->getContext(),
135                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
136     }
137     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
138   }
139   // We have something that might fold it's operand. Compare SCEVs.
140   if (!SE->isSCEVable(UseInst->getType()))
141     return nullptr;
142 
143   // Bypass the operand if SCEV can prove it has no effect.
144   if (SE->getSCEV(UseInst) != FoldedExpr)
145     return nullptr;
146 
147   DEBUG(dbgs() << "INDVARS: Eliminated IV operand: " << *IVOperand
148         << " -> " << *UseInst << '\n');
149 
150   UseInst->setOperand(OperIdx, IVSrc);
151   assert(SE->getSCEV(UseInst) == FoldedExpr && "bad SCEV with folded oper");
152 
153   ++NumElimOperand;
154   Changed = true;
155   if (IVOperand->use_empty())
156     DeadInsts.emplace_back(IVOperand);
157   return IVSrc;
158 }
159 
160 /// SimplifyIVUsers helper for eliminating useless
161 /// comparisons against an induction variable.
162 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
163   unsigned IVOperIdx = 0;
164   ICmpInst::Predicate Pred = ICmp->getPredicate();
165   ICmpInst::Predicate OriginalPred = Pred;
166   if (IVOperand != ICmp->getOperand(0)) {
167     // Swapped
168     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
169     IVOperIdx = 1;
170     Pred = ICmpInst::getSwappedPredicate(Pred);
171   }
172 
173   // Get the SCEVs for the ICmp operands.
174   const SCEV *S = SE->getSCEV(ICmp->getOperand(IVOperIdx));
175   const SCEV *X = SE->getSCEV(ICmp->getOperand(1 - IVOperIdx));
176 
177   // Simplify unnecessary loops away.
178   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
179   S = SE->getSCEVAtScope(S, ICmpLoop);
180   X = SE->getSCEVAtScope(X, ICmpLoop);
181 
182   ICmpInst::Predicate InvariantPredicate;
183   const SCEV *InvariantLHS, *InvariantRHS;
184 
185   // If the condition is always true or always false, replace it with
186   // a constant value.
187   if (SE->isKnownPredicate(Pred, S, X)) {
188     ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
189     DeadInsts.emplace_back(ICmp);
190     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
191   } else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X)) {
192     ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
193     DeadInsts.emplace_back(ICmp);
194     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
195   } else if (isa<PHINode>(IVOperand) &&
196              SE->isLoopInvariantPredicate(Pred, S, X, L, InvariantPredicate,
197                                           InvariantLHS, InvariantRHS)) {
198 
199     // Rewrite the comparison to a loop invariant comparison if it can be done
200     // cheaply, where cheaply means "we don't need to emit any new
201     // instructions".
202 
203     Value *NewLHS = nullptr, *NewRHS = nullptr;
204 
205     if (S == InvariantLHS || X == InvariantLHS)
206       NewLHS =
207           ICmp->getOperand(S == InvariantLHS ? IVOperIdx : (1 - IVOperIdx));
208 
209     if (S == InvariantRHS || X == InvariantRHS)
210       NewRHS =
211           ICmp->getOperand(S == InvariantRHS ? IVOperIdx : (1 - IVOperIdx));
212 
213     auto *PN = cast<PHINode>(IVOperand);
214     for (unsigned i = 0, e = PN->getNumIncomingValues();
215          i != e && (!NewLHS || !NewRHS);
216          ++i) {
217 
218       // If this is a value incoming from the backedge, then it cannot be a loop
219       // invariant value (since we know that IVOperand is an induction variable).
220       if (L->contains(PN->getIncomingBlock(i)))
221         continue;
222 
223       // NB! This following assert does not fundamentally have to be true, but
224       // it is true today given how SCEV analyzes induction variables.
225       // Specifically, today SCEV will *not* recognize %iv as an induction
226       // variable in the following case:
227       //
228       // define void @f(i32 %k) {
229       // entry:
230       //   br i1 undef, label %r, label %l
231       //
232       // l:
233       //   %k.inc.l = add i32 %k, 1
234       //   br label %loop
235       //
236       // r:
237       //   %k.inc.r = add i32 %k, 1
238       //   br label %loop
239       //
240       // loop:
241       //   %iv = phi i32 [ %k.inc.l, %l ], [ %k.inc.r, %r ], [ %iv.inc, %loop ]
242       //   %iv.inc = add i32 %iv, 1
243       //   br label %loop
244       // }
245       //
246       // but if it starts to, at some point, then the assertion below will have
247       // to be changed to a runtime check.
248 
249       Value *Incoming = PN->getIncomingValue(i);
250 
251 #ifndef NDEBUG
252       if (auto *I = dyn_cast<Instruction>(Incoming))
253         assert(DT->dominates(I, ICmp) && "Should be a unique loop dominating value!");
254 #endif
255 
256       const SCEV *IncomingS = SE->getSCEV(Incoming);
257 
258       if (!NewLHS && IncomingS == InvariantLHS)
259         NewLHS = Incoming;
260       if (!NewRHS && IncomingS == InvariantRHS)
261         NewRHS = Incoming;
262     }
263 
264     if (!NewLHS || !NewRHS)
265       // We could not find an existing value to replace either LHS or RHS.
266       // Generating new instructions has subtler tradeoffs, so avoid doing that
267       // for now.
268       return;
269 
270     DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
271     ICmp->setPredicate(InvariantPredicate);
272     ICmp->setOperand(0, NewLHS);
273     ICmp->setOperand(1, NewRHS);
274   } else if (ICmpInst::isSigned(OriginalPred) &&
275              SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
276     // If we were unable to make anything above, all we can is to canonicalize
277     // the comparison hoping that it will open the doors for other
278     // optimizations. If we find out that we compare two non-negative values,
279     // we turn the instruction's predicate to its unsigned version. Note that
280     // we cannot rely on Pred here unless we check if we have swapped it.
281     assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
282     DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp << '\n');
283     ICmp->setPredicate(ICmpInst::getUnsignedPredicate(OriginalPred));
284   } else
285     return;
286 
287   ++NumElimCmp;
288   Changed = true;
289 }
290 
291 bool SimplifyIndvar::eliminateSDiv(BinaryOperator *SDiv) {
292   // Get the SCEVs for the ICmp operands.
293   auto *N = SE->getSCEV(SDiv->getOperand(0));
294   auto *D = SE->getSCEV(SDiv->getOperand(1));
295 
296   // Simplify unnecessary loops away.
297   const Loop *L = LI->getLoopFor(SDiv->getParent());
298   N = SE->getSCEVAtScope(N, L);
299   D = SE->getSCEVAtScope(D, L);
300 
301   // Replace sdiv by udiv if both of the operands are non-negative
302   if (SE->isKnownNonNegative(N) && SE->isKnownNonNegative(D)) {
303     auto *UDiv = BinaryOperator::Create(
304         BinaryOperator::UDiv, SDiv->getOperand(0), SDiv->getOperand(1),
305         SDiv->getName() + ".udiv", SDiv);
306     UDiv->setIsExact(SDiv->isExact());
307     SDiv->replaceAllUsesWith(UDiv);
308     DEBUG(dbgs() << "INDVARS: Simplified sdiv: " << *SDiv << '\n');
309     ++NumSimplifiedSDiv;
310     Changed = true;
311     DeadInsts.push_back(SDiv);
312     return true;
313   }
314 
315   return false;
316 }
317 
318 // i %s n -> i %u n if i >= 0 and n >= 0
319 void SimplifyIndvar::replaceSRemWithURem(BinaryOperator *Rem) {
320   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
321   auto *URem = BinaryOperator::Create(BinaryOperator::URem, N, D,
322                                       Rem->getName() + ".urem", Rem);
323   Rem->replaceAllUsesWith(URem);
324   DEBUG(dbgs() << "INDVARS: Simplified srem: " << *Rem << '\n');
325   ++NumSimplifiedSRem;
326   Changed = true;
327   DeadInsts.emplace_back(Rem);
328 }
329 
330 // i % n  -->  i  if i is in [0,n).
331 void SimplifyIndvar::replaceRemWithNumerator(BinaryOperator *Rem) {
332   Rem->replaceAllUsesWith(Rem->getOperand(0));
333   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
334   ++NumElimRem;
335   Changed = true;
336   DeadInsts.emplace_back(Rem);
337 }
338 
339 // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
340 void SimplifyIndvar::replaceRemWithNumeratorOrZero(BinaryOperator *Rem) {
341   auto *T = Rem->getType();
342   auto *N = Rem->getOperand(0), *D = Rem->getOperand(1);
343   ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ, N, D);
344   SelectInst *Sel =
345       SelectInst::Create(ICmp, ConstantInt::get(T, 0), N, "iv.rem", Rem);
346   Rem->replaceAllUsesWith(Sel);
347   DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
348   ++NumElimRem;
349   Changed = true;
350   DeadInsts.emplace_back(Rem);
351 }
352 
353 /// SimplifyIVUsers helper for eliminating useless remainder operations
354 /// operating on an induction variable or replacing srem by urem.
355 void SimplifyIndvar::simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
356                                          bool IsSigned) {
357   auto *NValue = Rem->getOperand(0);
358   auto *DValue = Rem->getOperand(1);
359   // We're only interested in the case where we know something about
360   // the numerator, unless it is a srem, because we want to replace srem by urem
361   // in general.
362   bool UsedAsNumerator = IVOperand == NValue;
363   if (!UsedAsNumerator && !IsSigned)
364     return;
365 
366   const SCEV *N = SE->getSCEV(NValue);
367 
368   // Simplify unnecessary loops away.
369   const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
370   N = SE->getSCEVAtScope(N, ICmpLoop);
371 
372   bool IsNumeratorNonNegative = !IsSigned || SE->isKnownNonNegative(N);
373 
374   // Do not proceed if the Numerator may be negative
375   if (!IsNumeratorNonNegative)
376     return;
377 
378   const SCEV *D = SE->getSCEV(DValue);
379   D = SE->getSCEVAtScope(D, ICmpLoop);
380 
381   if (UsedAsNumerator) {
382     auto LT = IsSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT;
383     if (SE->isKnownPredicate(LT, N, D)) {
384       replaceRemWithNumerator(Rem);
385       return;
386     }
387 
388     auto *T = Rem->getType();
389     const auto *NLessOne = SE->getMinusSCEV(N, SE->getOne(T));
390     if (SE->isKnownPredicate(LT, NLessOne, D)) {
391       replaceRemWithNumeratorOrZero(Rem);
392       return;
393     }
394   }
395 
396   // Try to replace SRem with URem, if both N and D are known non-negative.
397   // Since we had already check N, we only need to check D now
398   if (!IsSigned || !SE->isKnownNonNegative(D))
399     return;
400 
401   replaceSRemWithURem(Rem);
402 }
403 
404 bool SimplifyIndvar::eliminateOverflowIntrinsic(CallInst *CI) {
405   auto *F = CI->getCalledFunction();
406   if (!F)
407     return false;
408 
409   typedef const SCEV *(ScalarEvolution::*OperationFunctionTy)(
410       const SCEV *, const SCEV *, SCEV::NoWrapFlags, unsigned);
411   typedef const SCEV *(ScalarEvolution::*ExtensionFunctionTy)(
412       const SCEV *, Type *, unsigned);
413 
414   OperationFunctionTy Operation;
415   ExtensionFunctionTy Extension;
416 
417   Instruction::BinaryOps RawOp;
418 
419   // We always have exactly one of nsw or nuw.  If NoSignedOverflow is false, we
420   // have nuw.
421   bool NoSignedOverflow;
422 
423   switch (F->getIntrinsicID()) {
424   default:
425     return false;
426 
427   case Intrinsic::sadd_with_overflow:
428     Operation = &ScalarEvolution::getAddExpr;
429     Extension = &ScalarEvolution::getSignExtendExpr;
430     RawOp = Instruction::Add;
431     NoSignedOverflow = true;
432     break;
433 
434   case Intrinsic::uadd_with_overflow:
435     Operation = &ScalarEvolution::getAddExpr;
436     Extension = &ScalarEvolution::getZeroExtendExpr;
437     RawOp = Instruction::Add;
438     NoSignedOverflow = false;
439     break;
440 
441   case Intrinsic::ssub_with_overflow:
442     Operation = &ScalarEvolution::getMinusSCEV;
443     Extension = &ScalarEvolution::getSignExtendExpr;
444     RawOp = Instruction::Sub;
445     NoSignedOverflow = true;
446     break;
447 
448   case Intrinsic::usub_with_overflow:
449     Operation = &ScalarEvolution::getMinusSCEV;
450     Extension = &ScalarEvolution::getZeroExtendExpr;
451     RawOp = Instruction::Sub;
452     NoSignedOverflow = false;
453     break;
454   }
455 
456   const SCEV *LHS = SE->getSCEV(CI->getArgOperand(0));
457   const SCEV *RHS = SE->getSCEV(CI->getArgOperand(1));
458 
459   auto *NarrowTy = cast<IntegerType>(LHS->getType());
460   auto *WideTy =
461     IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
462 
463   const SCEV *A =
464       (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
465                        WideTy, 0);
466   const SCEV *B =
467       (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
468                        (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
469 
470   if (A != B)
471     return false;
472 
473   // Proved no overflow, nuke the overflow check and, if possible, the overflow
474   // intrinsic as well.
475 
476   BinaryOperator *NewResult = BinaryOperator::Create(
477       RawOp, CI->getArgOperand(0), CI->getArgOperand(1), "", CI);
478 
479   if (NoSignedOverflow)
480     NewResult->setHasNoSignedWrap(true);
481   else
482     NewResult->setHasNoUnsignedWrap(true);
483 
484   SmallVector<ExtractValueInst *, 4> ToDelete;
485 
486   for (auto *U : CI->users()) {
487     if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
488       if (EVI->getIndices()[0] == 1)
489         EVI->replaceAllUsesWith(ConstantInt::getFalse(CI->getContext()));
490       else {
491         assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
492         EVI->replaceAllUsesWith(NewResult);
493       }
494       ToDelete.push_back(EVI);
495     }
496   }
497 
498   for (auto *EVI : ToDelete)
499     EVI->eraseFromParent();
500 
501   if (CI->use_empty())
502     CI->eraseFromParent();
503 
504   return true;
505 }
506 
507 /// Eliminate an operation that consumes a simple IV and has no observable
508 /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
509 /// but UseInst may not be.
510 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
511                                      Instruction *IVOperand) {
512   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
513     eliminateIVComparison(ICmp, IVOperand);
514     return true;
515   }
516   if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
517     bool IsSRem = Bin->getOpcode() == Instruction::SRem;
518     if (IsSRem || Bin->getOpcode() == Instruction::URem) {
519       simplifyIVRemainder(Bin, IVOperand, IsSRem);
520       return true;
521     }
522 
523     if (Bin->getOpcode() == Instruction::SDiv)
524       return eliminateSDiv(Bin);
525   }
526 
527   if (auto *CI = dyn_cast<CallInst>(UseInst))
528     if (eliminateOverflowIntrinsic(CI))
529       return true;
530 
531   if (eliminateIdentitySCEV(UseInst, IVOperand))
532     return true;
533 
534   return false;
535 }
536 
537 /// Eliminate any operation that SCEV can prove is an identity function.
538 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
539                                            Instruction *IVOperand) {
540   if (!SE->isSCEVable(UseInst->getType()) ||
541       (UseInst->getType() != IVOperand->getType()) ||
542       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
543     return false;
544 
545   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
546   // dominator tree, even if X is an operand to Y.  For instance, in
547   //
548   //     %iv = phi i32 {0,+,1}
549   //     br %cond, label %left, label %merge
550   //
551   //   left:
552   //     %X = add i32 %iv, 0
553   //     br label %merge
554   //
555   //   merge:
556   //     %M = phi (%X, %iv)
557   //
558   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
559   // %M.replaceAllUsesWith(%X) would be incorrect.
560 
561   if (isa<PHINode>(UseInst))
562     // If UseInst is not a PHI node then we know that IVOperand dominates
563     // UseInst directly from the legality of SSA.
564     if (!DT || !DT->dominates(IVOperand, UseInst))
565       return false;
566 
567   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
568     return false;
569 
570   DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
571 
572   UseInst->replaceAllUsesWith(IVOperand);
573   ++NumElimIdentity;
574   Changed = true;
575   DeadInsts.emplace_back(UseInst);
576   return true;
577 }
578 
579 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
580 /// unsigned-overflow.  Returns true if anything changed, false otherwise.
581 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
582                                                     Value *IVOperand) {
583 
584   // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
585   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
586     return false;
587 
588   const SCEV *(ScalarEvolution::*GetExprForBO)(const SCEV *, const SCEV *,
589                                                SCEV::NoWrapFlags, unsigned);
590   switch (BO->getOpcode()) {
591   default:
592     return false;
593 
594   case Instruction::Add:
595     GetExprForBO = &ScalarEvolution::getAddExpr;
596     break;
597 
598   case Instruction::Sub:
599     GetExprForBO = &ScalarEvolution::getMinusSCEV;
600     break;
601 
602   case Instruction::Mul:
603     GetExprForBO = &ScalarEvolution::getMulExpr;
604     break;
605   }
606 
607   unsigned BitWidth = cast<IntegerType>(BO->getType())->getBitWidth();
608   Type *WideTy = IntegerType::get(BO->getContext(), BitWidth * 2);
609   const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
610   const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
611 
612   bool Changed = false;
613 
614   if (!BO->hasNoUnsignedWrap()) {
615     const SCEV *ExtendAfterOp = SE->getZeroExtendExpr(SE->getSCEV(BO), WideTy);
616     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
617       SE->getZeroExtendExpr(LHS, WideTy), SE->getZeroExtendExpr(RHS, WideTy),
618       SCEV::FlagAnyWrap, 0u);
619     if (ExtendAfterOp == OpAfterExtend) {
620       BO->setHasNoUnsignedWrap();
621       SE->forgetValue(BO);
622       Changed = true;
623     }
624   }
625 
626   if (!BO->hasNoSignedWrap()) {
627     const SCEV *ExtendAfterOp = SE->getSignExtendExpr(SE->getSCEV(BO), WideTy);
628     const SCEV *OpAfterExtend = (SE->*GetExprForBO)(
629       SE->getSignExtendExpr(LHS, WideTy), SE->getSignExtendExpr(RHS, WideTy),
630       SCEV::FlagAnyWrap, 0u);
631     if (ExtendAfterOp == OpAfterExtend) {
632       BO->setHasNoSignedWrap();
633       SE->forgetValue(BO);
634       Changed = true;
635     }
636   }
637 
638   return Changed;
639 }
640 
641 /// Annotate the Shr in (X << IVOperand) >> C as exact using the
642 /// information from the IV's range. Returns true if anything changed, false
643 /// otherwise.
644 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
645                                           Value *IVOperand) {
646   using namespace llvm::PatternMatch;
647 
648   if (BO->getOpcode() == Instruction::Shl) {
649     bool Changed = false;
650     ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
651     for (auto *U : BO->users()) {
652       const APInt *C;
653       if (match(U,
654                 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
655           match(U,
656                 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
657         BinaryOperator *Shr = cast<BinaryOperator>(U);
658         if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
659           Shr->setIsExact(true);
660           Changed = true;
661         }
662       }
663     }
664     return Changed;
665   }
666 
667   return false;
668 }
669 
670 /// Add all uses of Def to the current IV's worklist.
671 static void pushIVUsers(
672   Instruction *Def,
673   SmallPtrSet<Instruction*,16> &Simplified,
674   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
675 
676   for (User *U : Def->users()) {
677     Instruction *UI = cast<Instruction>(U);
678 
679     // Avoid infinite or exponential worklist processing.
680     // Also ensure unique worklist users.
681     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
682     // self edges first.
683     if (UI != Def && Simplified.insert(UI).second)
684       SimpleIVUsers.push_back(std::make_pair(UI, Def));
685   }
686 }
687 
688 /// Return true if this instruction generates a simple SCEV
689 /// expression in terms of that IV.
690 ///
691 /// This is similar to IVUsers' isInteresting() but processes each instruction
692 /// non-recursively when the operand is already known to be a simpleIVUser.
693 ///
694 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
695   if (!SE->isSCEVable(I->getType()))
696     return false;
697 
698   // Get the symbolic expression for this instruction.
699   const SCEV *S = SE->getSCEV(I);
700 
701   // Only consider affine recurrences.
702   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
703   if (AR && AR->getLoop() == L)
704     return true;
705 
706   return false;
707 }
708 
709 /// Iteratively perform simplification on a worklist of users
710 /// of the specified induction variable. Each successive simplification may push
711 /// more users which may themselves be candidates for simplification.
712 ///
713 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
714 /// instructions in-place during analysis. Rather than rewriting induction
715 /// variables bottom-up from their users, it transforms a chain of IVUsers
716 /// top-down, updating the IR only when it encounters a clear optimization
717 /// opportunity.
718 ///
719 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
720 ///
721 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
722   if (!SE->isSCEVable(CurrIV->getType()))
723     return;
724 
725   // Instructions processed by SimplifyIndvar for CurrIV.
726   SmallPtrSet<Instruction*,16> Simplified;
727 
728   // Use-def pairs if IV users waiting to be processed for CurrIV.
729   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
730 
731   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
732   // called multiple times for the same LoopPhi. This is the proper thing to
733   // do for loop header phis that use each other.
734   pushIVUsers(CurrIV, Simplified, SimpleIVUsers);
735 
736   while (!SimpleIVUsers.empty()) {
737     std::pair<Instruction*, Instruction*> UseOper =
738       SimpleIVUsers.pop_back_val();
739     Instruction *UseInst = UseOper.first;
740 
741     // Bypass back edges to avoid extra work.
742     if (UseInst == CurrIV) continue;
743 
744     Instruction *IVOperand = UseOper.second;
745     for (unsigned N = 0; IVOperand; ++N) {
746       assert(N <= Simplified.size() && "runaway iteration");
747 
748       Value *NewOper = foldIVUser(UseOper.first, IVOperand);
749       if (!NewOper)
750         break; // done folding
751       IVOperand = dyn_cast<Instruction>(NewOper);
752     }
753     if (!IVOperand)
754       continue;
755 
756     if (eliminateIVUser(UseOper.first, IVOperand)) {
757       pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
758       continue;
759     }
760 
761     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseOper.first)) {
762       if ((isa<OverflowingBinaryOperator>(BO) &&
763            strengthenOverflowingOperation(BO, IVOperand)) ||
764           (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
765         // re-queue uses of the now modified binary operator and fall
766         // through to the checks that remain.
767         pushIVUsers(IVOperand, Simplified, SimpleIVUsers);
768       }
769     }
770 
771     CastInst *Cast = dyn_cast<CastInst>(UseOper.first);
772     if (V && Cast) {
773       V->visitCast(Cast);
774       continue;
775     }
776     if (isSimpleIVUser(UseOper.first, L, SE)) {
777       pushIVUsers(UseOper.first, Simplified, SimpleIVUsers);
778     }
779   }
780 }
781 
782 namespace llvm {
783 
784 void IVVisitor::anchor() { }
785 
786 /// Simplify instructions that use this induction variable
787 /// by using ScalarEvolution to analyze the IV's recurrence.
788 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
789                        LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead,
790                        IVVisitor *V) {
791   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, Dead);
792   SIV.simplifyUsers(CurrIV, V);
793   return SIV.hasChanged();
794 }
795 
796 /// Simplify users of induction variables within this
797 /// loop. This does not actually change or add IVs.
798 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
799                      LoopInfo *LI, SmallVectorImpl<WeakTrackingVH> &Dead) {
800   bool Changed = false;
801   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
802     Changed |= simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, Dead);
803   }
804   return Changed;
805 }
806 
807 } // namespace llvm
808