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