1 //===-- SimplifyIndVar.cpp - Induction variable simplification ------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 //
9 // This file implements induction variable simplification. It does
10 // not define any actual pass or policy, but provides a single function to
11 // simplify a loop's induction variables based on ScalarEvolution.
12 //
13 //===----------------------------------------------------------------------===//
14 
15 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
16 #include "llvm/ADT/STLExtras.h"
17 #include "llvm/ADT/SmallVector.h"
18 #include "llvm/ADT/Statistic.h"
19 #include "llvm/Analysis/LoopInfo.h"
20 #include "llvm/IR/DataLayout.h"
21 #include "llvm/IR/Dominators.h"
22 #include "llvm/IR/IRBuilder.h"
23 #include "llvm/IR/Instructions.h"
24 #include "llvm/IR/IntrinsicInst.h"
25 #include "llvm/IR/PatternMatch.h"
26 #include "llvm/Support/Debug.h"
27 #include "llvm/Support/raw_ostream.h"
28 #include "llvm/Transforms/Utils/Local.h"
29 #include "llvm/Transforms/Utils/ScalarEvolutionExpander.h"
30 
31 using namespace llvm;
32 
33 #define DEBUG_TYPE "indvars"
34 
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");
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     const TargetTransformInfo *TTI;
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, const TargetTransformInfo *TTI,
66                    SCEVExpander &Rewriter,
67                    SmallVectorImpl<WeakTrackingVH> &Dead)
68         : L(Loop), LI(LI), SE(SE), DT(DT), TTI(TTI), Rewriter(Rewriter),
69           DeadInsts(Dead), Changed(false) {
70       assert(LI && "IV simplification requires LoopInfo");
71     }
72 
73     bool hasChanged() const { return Changed; }
74 
75     /// Iteratively perform simplification on a worklist of users of the
76     /// specified induction variable. This is the top-level driver that applies
77     /// all simplifications to users of an IV.
78     void simplifyUsers(PHINode *CurrIV, IVVisitor *V = nullptr);
79 
80     Value *foldIVUser(Instruction *UseInst, Instruction *IVOperand);
81 
82     bool eliminateIdentitySCEV(Instruction *UseInst, Instruction *IVOperand);
83     bool replaceIVUserWithLoopInvariant(Instruction *UseInst);
84 
85     bool eliminateOverflowIntrinsic(WithOverflowInst *WO);
86     bool eliminateSaturatingIntrinsic(SaturatingInst *SI);
87     bool eliminateTrunc(TruncInst *TI);
88     bool eliminateIVUser(Instruction *UseInst, Instruction *IVOperand);
89     bool makeIVComparisonInvariant(ICmpInst *ICmp, Value *IVOperand);
90     void eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand);
91     void simplifyIVRemainder(BinaryOperator *Rem, Value *IVOperand,
92                              bool IsSigned);
93     void replaceRemWithNumerator(BinaryOperator *Rem);
94     void replaceRemWithNumeratorOrZero(BinaryOperator *Rem);
95     void replaceSRemWithURem(BinaryOperator *Rem);
96     bool eliminateSDiv(BinaryOperator *SDiv);
97     bool strengthenOverflowingOperation(BinaryOperator *OBO, Value *IVOperand);
98     bool strengthenRightShift(BinaryOperator *BO, Value *IVOperand);
99   };
100 }
101 
102 /// Fold an IV operand into its use.  This removes increments of an
103 /// aligned IV when used by a instruction that ignores the low bits.
104 ///
105 /// IVOperand is guaranteed SCEVable, but UseInst may not be.
106 ///
107 /// Return the operand of IVOperand for this induction variable if IVOperand can
108 /// be folded (in case more folding opportunities have been exposed).
109 /// Otherwise return null.
110 Value *SimplifyIndvar::foldIVUser(Instruction *UseInst, Instruction *IVOperand) {
111   Value *IVSrc = nullptr;
112   const unsigned OperIdx = 0;
113   const SCEV *FoldedExpr = nullptr;
114   bool MustDropExactFlag = false;
115   switch (UseInst->getOpcode()) {
116   default:
117     return nullptr;
118   case Instruction::UDiv:
119   case Instruction::LShr:
120     // We're only interested in the case where we know something about
121     // the numerator and have a constant denominator.
122     if (IVOperand != UseInst->getOperand(OperIdx) ||
123         !isa<ConstantInt>(UseInst->getOperand(1)))
124       return nullptr;
125 
126     // Attempt to fold a binary operator with constant operand.
127     // e.g. ((I + 1) >> 2) => I >> 2
128     if (!isa<BinaryOperator>(IVOperand)
129         || !isa<ConstantInt>(IVOperand->getOperand(1)))
130       return nullptr;
131 
132     IVSrc = IVOperand->getOperand(0);
133     // IVSrc must be the (SCEVable) IV, since the other operand is const.
134     assert(SE->isSCEVable(IVSrc->getType()) && "Expect SCEVable IV operand");
135 
136     ConstantInt *D = cast<ConstantInt>(UseInst->getOperand(1));
137     if (UseInst->getOpcode() == Instruction::LShr) {
138       // Get a constant for the divisor. See createSCEV.
139       uint32_t BitWidth = cast<IntegerType>(UseInst->getType())->getBitWidth();
140       if (D->getValue().uge(BitWidth))
141         return nullptr;
142 
143       D = ConstantInt::get(UseInst->getContext(),
144                            APInt::getOneBitSet(BitWidth, D->getZExtValue()));
145     }
146     FoldedExpr = SE->getUDivExpr(SE->getSCEV(IVSrc), SE->getSCEV(D));
147     // We might have 'exact' flag set at this point which will no longer be
148     // correct after we make the replacement.
149     if (UseInst->isExact() &&
150         SE->getSCEV(IVSrc) != SE->getMulExpr(FoldedExpr, SE->getSCEV(D)))
151       MustDropExactFlag = true;
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   LLVM_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   if (MustDropExactFlag)
168     UseInst->dropPoisonGeneratingFlags();
169 
170   ++NumElimOperand;
171   Changed = true;
172   if (IVOperand->use_empty())
173     DeadInsts.emplace_back(IVOperand);
174   return IVSrc;
175 }
176 
177 bool SimplifyIndvar::makeIVComparisonInvariant(ICmpInst *ICmp,
178                                                Value *IVOperand) {
179   unsigned IVOperIdx = 0;
180   ICmpInst::Predicate Pred = ICmp->getPredicate();
181   if (IVOperand != ICmp->getOperand(0)) {
182     // Swapped
183     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
184     IVOperIdx = 1;
185     Pred = ICmpInst::getSwappedPredicate(Pred);
186   }
187 
188   // Get the SCEVs for the ICmp operands (in the specific context of the
189   // current loop)
190   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
191   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
192   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
193 
194   auto *PN = dyn_cast<PHINode>(IVOperand);
195   if (!PN)
196     return false;
197   auto LIP = SE->getLoopInvariantPredicate(Pred, S, X, L);
198   if (!LIP)
199     return false;
200   ICmpInst::Predicate InvariantPredicate = LIP->Pred;
201   const SCEV *InvariantLHS = LIP->LHS;
202   const SCEV *InvariantRHS = LIP->RHS;
203 
204   // Rewrite the comparison to a loop invariant comparison if it can be done
205   // cheaply, where cheaply means "we don't need to emit any new
206   // instructions".
207 
208   SmallDenseMap<const SCEV*, Value*> CheapExpansions;
209   CheapExpansions[S] = ICmp->getOperand(IVOperIdx);
210   CheapExpansions[X] = ICmp->getOperand(1 - IVOperIdx);
211 
212   // TODO: Support multiple entry loops?  (We currently bail out of these in
213   // the IndVarSimplify pass)
214   if (auto *BB = L->getLoopPredecessor()) {
215     const int Idx = PN->getBasicBlockIndex(BB);
216     if (Idx >= 0) {
217       Value *Incoming = PN->getIncomingValue(Idx);
218       const SCEV *IncomingS = SE->getSCEV(Incoming);
219       CheapExpansions[IncomingS] = Incoming;
220     }
221   }
222   Value *NewLHS = CheapExpansions[InvariantLHS];
223   Value *NewRHS = CheapExpansions[InvariantRHS];
224 
225   if (!NewLHS)
226     if (auto *ConstLHS = dyn_cast<SCEVConstant>(InvariantLHS))
227       NewLHS = ConstLHS->getValue();
228   if (!NewRHS)
229     if (auto *ConstRHS = dyn_cast<SCEVConstant>(InvariantRHS))
230       NewRHS = ConstRHS->getValue();
231 
232   if (!NewLHS || !NewRHS)
233     // We could not find an existing value to replace either LHS or RHS.
234     // Generating new instructions has subtler tradeoffs, so avoid doing that
235     // for now.
236     return false;
237 
238   LLVM_DEBUG(dbgs() << "INDVARS: Simplified comparison: " << *ICmp << '\n');
239   ICmp->setPredicate(InvariantPredicate);
240   ICmp->setOperand(0, NewLHS);
241   ICmp->setOperand(1, NewRHS);
242   return true;
243 }
244 
245 /// SimplifyIVUsers helper for eliminating useless
246 /// comparisons against an induction variable.
247 void SimplifyIndvar::eliminateIVComparison(ICmpInst *ICmp, Value *IVOperand) {
248   unsigned IVOperIdx = 0;
249   ICmpInst::Predicate Pred = ICmp->getPredicate();
250   ICmpInst::Predicate OriginalPred = Pred;
251   if (IVOperand != ICmp->getOperand(0)) {
252     // Swapped
253     assert(IVOperand == ICmp->getOperand(1) && "Can't find IVOperand");
254     IVOperIdx = 1;
255     Pred = ICmpInst::getSwappedPredicate(Pred);
256   }
257 
258   // Get the SCEVs for the ICmp operands (in the specific context of the
259   // current loop)
260   const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
261   const SCEV *S = SE->getSCEVAtScope(ICmp->getOperand(IVOperIdx), ICmpLoop);
262   const SCEV *X = SE->getSCEVAtScope(ICmp->getOperand(1 - IVOperIdx), ICmpLoop);
263 
264   // If the condition is always true or always false in the given context,
265   // replace it with a constant value.
266   // TODO: We can sharpen the context to common dominator of all ICmp's users.
267   if (auto Ev = SE->evaluatePredicateAt(Pred, S, X, ICmp)) {
268     ICmp->replaceAllUsesWith(ConstantInt::getBool(ICmp->getContext(), *Ev));
269     DeadInsts.emplace_back(ICmp);
270     LLVM_DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
271   } else if (makeIVComparisonInvariant(ICmp, IVOperand)) {
272     // fallthrough to end of function
273   } else if (ICmpInst::isSigned(OriginalPred) &&
274              SE->isKnownNonNegative(S) && SE->isKnownNonNegative(X)) {
275     // If we were unable to make anything above, all we can is to canonicalize
276     // the comparison hoping that it will open the doors for other
277     // optimizations. If we find out that we compare two non-negative values,
278     // we turn the instruction's predicate to its unsigned version. Note that
279     // we cannot rely on Pred here unless we check if we have swapped it.
280     assert(ICmp->getPredicate() == OriginalPred && "Predicate changed?");
281     LLVM_DEBUG(dbgs() << "INDVARS: Turn to unsigned comparison: " << *ICmp
282                       << '\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     LLVM_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   LLVM_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   LLVM_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   LLVM_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 static bool willNotOverflow(ScalarEvolution *SE, Instruction::BinaryOps BinOp,
405                             bool Signed, const SCEV *LHS, const SCEV *RHS) {
406   const SCEV *(ScalarEvolution::*Operation)(const SCEV *, const SCEV *,
407                                             SCEV::NoWrapFlags, unsigned);
408   switch (BinOp) {
409   default:
410     llvm_unreachable("Unsupported binary op");
411   case Instruction::Add:
412     Operation = &ScalarEvolution::getAddExpr;
413     break;
414   case Instruction::Sub:
415     Operation = &ScalarEvolution::getMinusSCEV;
416     break;
417   case Instruction::Mul:
418     Operation = &ScalarEvolution::getMulExpr;
419     break;
420   }
421 
422   const SCEV *(ScalarEvolution::*Extension)(const SCEV *, Type *, unsigned) =
423       Signed ? &ScalarEvolution::getSignExtendExpr
424              : &ScalarEvolution::getZeroExtendExpr;
425 
426   // Check ext(LHS op RHS) == ext(LHS) op ext(RHS)
427   auto *NarrowTy = cast<IntegerType>(LHS->getType());
428   auto *WideTy =
429     IntegerType::get(NarrowTy->getContext(), NarrowTy->getBitWidth() * 2);
430 
431   const SCEV *A =
432       (SE->*Extension)((SE->*Operation)(LHS, RHS, SCEV::FlagAnyWrap, 0),
433                        WideTy, 0);
434   const SCEV *B =
435       (SE->*Operation)((SE->*Extension)(LHS, WideTy, 0),
436                        (SE->*Extension)(RHS, WideTy, 0), SCEV::FlagAnyWrap, 0);
437   return A == B;
438 }
439 
440 bool SimplifyIndvar::eliminateOverflowIntrinsic(WithOverflowInst *WO) {
441   const SCEV *LHS = SE->getSCEV(WO->getLHS());
442   const SCEV *RHS = SE->getSCEV(WO->getRHS());
443   if (!willNotOverflow(SE, WO->getBinaryOp(), WO->isSigned(), LHS, RHS))
444     return false;
445 
446   // Proved no overflow, nuke the overflow check and, if possible, the overflow
447   // intrinsic as well.
448 
449   BinaryOperator *NewResult = BinaryOperator::Create(
450       WO->getBinaryOp(), WO->getLHS(), WO->getRHS(), "", WO);
451 
452   if (WO->isSigned())
453     NewResult->setHasNoSignedWrap(true);
454   else
455     NewResult->setHasNoUnsignedWrap(true);
456 
457   SmallVector<ExtractValueInst *, 4> ToDelete;
458 
459   for (auto *U : WO->users()) {
460     if (auto *EVI = dyn_cast<ExtractValueInst>(U)) {
461       if (EVI->getIndices()[0] == 1)
462         EVI->replaceAllUsesWith(ConstantInt::getFalse(WO->getContext()));
463       else {
464         assert(EVI->getIndices()[0] == 0 && "Only two possibilities!");
465         EVI->replaceAllUsesWith(NewResult);
466       }
467       ToDelete.push_back(EVI);
468     }
469   }
470 
471   for (auto *EVI : ToDelete)
472     EVI->eraseFromParent();
473 
474   if (WO->use_empty())
475     WO->eraseFromParent();
476 
477   Changed = true;
478   return true;
479 }
480 
481 bool SimplifyIndvar::eliminateSaturatingIntrinsic(SaturatingInst *SI) {
482   const SCEV *LHS = SE->getSCEV(SI->getLHS());
483   const SCEV *RHS = SE->getSCEV(SI->getRHS());
484   if (!willNotOverflow(SE, SI->getBinaryOp(), SI->isSigned(), LHS, RHS))
485     return false;
486 
487   BinaryOperator *BO = BinaryOperator::Create(
488       SI->getBinaryOp(), SI->getLHS(), SI->getRHS(), SI->getName(), SI);
489   if (SI->isSigned())
490     BO->setHasNoSignedWrap();
491   else
492     BO->setHasNoUnsignedWrap();
493 
494   SI->replaceAllUsesWith(BO);
495   DeadInsts.emplace_back(SI);
496   Changed = true;
497   return true;
498 }
499 
500 bool SimplifyIndvar::eliminateTrunc(TruncInst *TI) {
501   // It is always legal to replace
502   //   icmp <pred> i32 trunc(iv), n
503   // with
504   //   icmp <pred> i64 sext(trunc(iv)), sext(n), if pred is signed predicate.
505   // Or with
506   //   icmp <pred> i64 zext(trunc(iv)), zext(n), if pred is unsigned predicate.
507   // Or with either of these if pred is an equality predicate.
508   //
509   // If we can prove that iv == sext(trunc(iv)) or iv == zext(trunc(iv)) for
510   // every comparison which uses trunc, it means that we can replace each of
511   // them with comparison of iv against sext/zext(n). We no longer need trunc
512   // after that.
513   //
514   // TODO: Should we do this if we can widen *some* comparisons, but not all
515   // of them? Sometimes it is enough to enable other optimizations, but the
516   // trunc instruction will stay in the loop.
517   Value *IV = TI->getOperand(0);
518   Type *IVTy = IV->getType();
519   const SCEV *IVSCEV = SE->getSCEV(IV);
520   const SCEV *TISCEV = SE->getSCEV(TI);
521 
522   // Check if iv == zext(trunc(iv)) and if iv == sext(trunc(iv)). If so, we can
523   // get rid of trunc
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;
530 
531   // If neither sext nor zext does collapse, it is not profitable to do any
532   // transform. Bail.
533   if (!DoesSExtCollapse && !DoesZExtCollapse)
534     return false;
535 
536   // Collect users of the trunc that look like comparisons against invariants.
537   // Bail if we find something different.
538   SmallVector<ICmpInst *, 4> ICmpUsers;
539   for (auto *U : TI->users()) {
540     // We don't care about users in unreachable blocks.
541     if (isa<Instruction>(U) &&
542         !DT->isReachableFromEntry(cast<Instruction>(U)->getParent()))
543       continue;
544     ICmpInst *ICI = dyn_cast<ICmpInst>(U);
545     if (!ICI) return false;
546     assert(L->contains(ICI->getParent()) && "LCSSA form broken?");
547     if (!(ICI->getOperand(0) == TI && L->isLoopInvariant(ICI->getOperand(1))) &&
548         !(ICI->getOperand(1) == TI && L->isLoopInvariant(ICI->getOperand(0))))
549       return false;
550     // If we cannot get rid of trunc, bail.
551     if (ICI->isSigned() && !DoesSExtCollapse)
552       return false;
553     if (ICI->isUnsigned() && !DoesZExtCollapse)
554       return false;
555     // For equality, either signed or unsigned works.
556     ICmpUsers.push_back(ICI);
557   }
558 
559   auto CanUseZExt = [&](ICmpInst *ICI) {
560     // Unsigned comparison can be widened as unsigned.
561     if (ICI->isUnsigned())
562       return true;
563     // Is it profitable to do zext?
564     if (!DoesZExtCollapse)
565       return false;
566     // For equality, we can safely zext both parts.
567     if (ICI->isEquality())
568       return true;
569     // Otherwise we can only use zext when comparing two non-negative or two
570     // negative values. But in practice, we will never pass DoesZExtCollapse
571     // check for a negative value, because zext(trunc(x)) is non-negative. So
572     // it only make sense to check for non-negativity here.
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);
576   };
577   // Replace all comparisons against trunc with comparisons against IV.
578   for (auto *ICI : ICmpUsers) {
579     bool IsSwapped = L->isLoopInvariant(ICI->getOperand(0));
580     auto *Op1 = IsSwapped ? ICI->getOperand(0) : ICI->getOperand(1);
581     Instruction *Ext = nullptr;
582     // For signed/unsigned predicate, replace the old comparison with comparison
583     // of immediate IV against sext/zext of the invariant argument. If we can
584     // use either sext or zext (i.e. we are dealing with equality predicate),
585     // then prefer zext as a more canonical form.
586     // TODO: If we see a signed comparison which can be turned into unsigned,
587     // we can do it here for canonicalization purposes.
588     ICmpInst::Predicate Pred = ICI->getPredicate();
589     if (IsSwapped) Pred = ICmpInst::getSwappedPredicate(Pred);
590     if (CanUseZExt(ICI)) {
591       assert(DoesZExtCollapse && "Unprofitable zext?");
592       Ext = new ZExtInst(Op1, IVTy, "zext", ICI);
593       Pred = ICmpInst::getUnsignedPredicate(Pred);
594     } else {
595       assert(DoesSExtCollapse && "Unprofitable sext?");
596       Ext = new SExtInst(Op1, IVTy, "sext", ICI);
597       assert(Pred == ICmpInst::getSignedPredicate(Pred) && "Must be signed!");
598     }
599     bool Changed;
600     L->makeLoopInvariant(Ext, Changed);
601     (void)Changed;
602     ICmpInst *NewICI = new ICmpInst(ICI, Pred, IV, Ext);
603     ICI->replaceAllUsesWith(NewICI);
604     DeadInsts.emplace_back(ICI);
605   }
606 
607   // Trunc no longer needed.
608   TI->replaceAllUsesWith(UndefValue::get(TI->getType()));
609   DeadInsts.emplace_back(TI);
610   return true;
611 }
612 
613 /// Eliminate an operation that consumes a simple IV and has no observable
614 /// side-effect given the range of IV values.  IVOperand is guaranteed SCEVable,
615 /// but UseInst may not be.
616 bool SimplifyIndvar::eliminateIVUser(Instruction *UseInst,
617                                      Instruction *IVOperand) {
618   if (ICmpInst *ICmp = dyn_cast<ICmpInst>(UseInst)) {
619     eliminateIVComparison(ICmp, IVOperand);
620     return true;
621   }
622   if (BinaryOperator *Bin = dyn_cast<BinaryOperator>(UseInst)) {
623     bool IsSRem = Bin->getOpcode() == Instruction::SRem;
624     if (IsSRem || Bin->getOpcode() == Instruction::URem) {
625       simplifyIVRemainder(Bin, IVOperand, IsSRem);
626       return true;
627     }
628 
629     if (Bin->getOpcode() == Instruction::SDiv)
630       return eliminateSDiv(Bin);
631   }
632 
633   if (auto *WO = dyn_cast<WithOverflowInst>(UseInst))
634     if (eliminateOverflowIntrinsic(WO))
635       return true;
636 
637   if (auto *SI = dyn_cast<SaturatingInst>(UseInst))
638     if (eliminateSaturatingIntrinsic(SI))
639       return true;
640 
641   if (auto *TI = dyn_cast<TruncInst>(UseInst))
642     if (eliminateTrunc(TI))
643       return true;
644 
645   if (eliminateIdentitySCEV(UseInst, IVOperand))
646     return true;
647 
648   return false;
649 }
650 
651 static Instruction *GetLoopInvariantInsertPosition(Loop *L, Instruction *Hint) {
652   if (auto *BB = L->getLoopPreheader())
653     return BB->getTerminator();
654 
655   return Hint;
656 }
657 
658 /// Replace the UseInst with a loop invariant expression if it is safe.
659 bool SimplifyIndvar::replaceIVUserWithLoopInvariant(Instruction *I) {
660   if (!SE->isSCEVable(I->getType()))
661     return false;
662 
663   // Get the symbolic expression for this instruction.
664   const SCEV *S = SE->getSCEV(I);
665 
666   if (!SE->isLoopInvariant(S, L))
667     return false;
668 
669   // Do not generate something ridiculous even if S is loop invariant.
670   if (Rewriter.isHighCostExpansion(S, L, SCEVCheapExpansionBudget, TTI, I))
671     return false;
672 
673   auto *IP = GetLoopInvariantInsertPosition(L, I);
674 
675   if (!isSafeToExpandAt(S, IP, *SE)) {
676     LLVM_DEBUG(dbgs() << "INDVARS: Can not replace IV user: " << *I
677                       << " with non-speculable loop invariant: " << *S << '\n');
678     return false;
679   }
680 
681   auto *Invariant = Rewriter.expandCodeFor(S, I->getType(), IP);
682 
683   I->replaceAllUsesWith(Invariant);
684   LLVM_DEBUG(dbgs() << "INDVARS: Replace IV user: " << *I
685                     << " with loop invariant: " << *S << '\n');
686   ++NumFoldedUser;
687   Changed = true;
688   DeadInsts.emplace_back(I);
689   return true;
690 }
691 
692 /// Eliminate any operation that SCEV can prove is an identity function.
693 bool SimplifyIndvar::eliminateIdentitySCEV(Instruction *UseInst,
694                                            Instruction *IVOperand) {
695   if (!SE->isSCEVable(UseInst->getType()) ||
696       (UseInst->getType() != IVOperand->getType()) ||
697       (SE->getSCEV(UseInst) != SE->getSCEV(IVOperand)))
698     return false;
699 
700   // getSCEV(X) == getSCEV(Y) does not guarantee that X and Y are related in the
701   // dominator tree, even if X is an operand to Y.  For instance, in
702   //
703   //     %iv = phi i32 {0,+,1}
704   //     br %cond, label %left, label %merge
705   //
706   //   left:
707   //     %X = add i32 %iv, 0
708   //     br label %merge
709   //
710   //   merge:
711   //     %M = phi (%X, %iv)
712   //
713   // getSCEV(%M) == getSCEV(%X) == {0,+,1}, but %X does not dominate %M, and
714   // %M.replaceAllUsesWith(%X) would be incorrect.
715 
716   if (isa<PHINode>(UseInst))
717     // If UseInst is not a PHI node then we know that IVOperand dominates
718     // UseInst directly from the legality of SSA.
719     if (!DT || !DT->dominates(IVOperand, UseInst))
720       return false;
721 
722   if (!LI->replacementPreservesLCSSAForm(UseInst, IVOperand))
723     return false;
724 
725   LLVM_DEBUG(dbgs() << "INDVARS: Eliminated identity: " << *UseInst << '\n');
726 
727   UseInst->replaceAllUsesWith(IVOperand);
728   ++NumElimIdentity;
729   Changed = true;
730   DeadInsts.emplace_back(UseInst);
731   return true;
732 }
733 
734 /// Annotate BO with nsw / nuw if it provably does not signed-overflow /
735 /// unsigned-overflow.  Returns true if anything changed, false otherwise.
736 bool SimplifyIndvar::strengthenOverflowingOperation(BinaryOperator *BO,
737                                                     Value *IVOperand) {
738   // Fastpath: we don't have any work to do if `BO` is `nuw` and `nsw`.
739   if (BO->hasNoUnsignedWrap() && BO->hasNoSignedWrap())
740     return false;
741 
742   if (BO->getOpcode() != Instruction::Add &&
743       BO->getOpcode() != Instruction::Sub &&
744       BO->getOpcode() != Instruction::Mul)
745     return false;
746 
747   const SCEV *LHS = SE->getSCEV(BO->getOperand(0));
748   const SCEV *RHS = SE->getSCEV(BO->getOperand(1));
749   bool Changed = false;
750 
751   if (!BO->hasNoUnsignedWrap() &&
752       willNotOverflow(SE, BO->getOpcode(), /* Signed */ false, LHS, RHS)) {
753     BO->setHasNoUnsignedWrap();
754     SE->forgetValue(BO);
755     Changed = true;
756   }
757 
758   if (!BO->hasNoSignedWrap() &&
759       willNotOverflow(SE, BO->getOpcode(), /* Signed */ true, LHS, RHS)) {
760     BO->setHasNoSignedWrap();
761     SE->forgetValue(BO);
762     Changed = true;
763   }
764 
765   return Changed;
766 }
767 
768 /// Annotate the Shr in (X << IVOperand) >> C as exact using the
769 /// information from the IV's range. Returns true if anything changed, false
770 /// otherwise.
771 bool SimplifyIndvar::strengthenRightShift(BinaryOperator *BO,
772                                           Value *IVOperand) {
773   using namespace llvm::PatternMatch;
774 
775   if (BO->getOpcode() == Instruction::Shl) {
776     bool Changed = false;
777     ConstantRange IVRange = SE->getUnsignedRange(SE->getSCEV(IVOperand));
778     for (auto *U : BO->users()) {
779       const APInt *C;
780       if (match(U,
781                 m_AShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C))) ||
782           match(U,
783                 m_LShr(m_Shl(m_Value(), m_Specific(IVOperand)), m_APInt(C)))) {
784         BinaryOperator *Shr = cast<BinaryOperator>(U);
785         if (!Shr->isExact() && IVRange.getUnsignedMin().uge(*C)) {
786           Shr->setIsExact(true);
787           Changed = true;
788         }
789       }
790     }
791     return Changed;
792   }
793 
794   return false;
795 }
796 
797 /// Add all uses of Def to the current IV's worklist.
798 static void pushIVUsers(
799   Instruction *Def, Loop *L,
800   SmallPtrSet<Instruction*,16> &Simplified,
801   SmallVectorImpl< std::pair<Instruction*,Instruction*> > &SimpleIVUsers) {
802 
803   for (User *U : Def->users()) {
804     Instruction *UI = cast<Instruction>(U);
805 
806     // Avoid infinite or exponential worklist processing.
807     // Also ensure unique worklist users.
808     // If Def is a LoopPhi, it may not be in the Simplified set, so check for
809     // self edges first.
810     if (UI == Def)
811       continue;
812 
813     // Only change the current Loop, do not change the other parts (e.g. other
814     // Loops).
815     if (!L->contains(UI))
816       continue;
817 
818     // Do not push the same instruction more than once.
819     if (!Simplified.insert(UI).second)
820       continue;
821 
822     SimpleIVUsers.push_back(std::make_pair(UI, Def));
823   }
824 }
825 
826 /// Return true if this instruction generates a simple SCEV
827 /// expression in terms of that IV.
828 ///
829 /// This is similar to IVUsers' isInteresting() but processes each instruction
830 /// non-recursively when the operand is already known to be a simpleIVUser.
831 ///
832 static bool isSimpleIVUser(Instruction *I, const Loop *L, ScalarEvolution *SE) {
833   if (!SE->isSCEVable(I->getType()))
834     return false;
835 
836   // Get the symbolic expression for this instruction.
837   const SCEV *S = SE->getSCEV(I);
838 
839   // Only consider affine recurrences.
840   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S);
841   if (AR && AR->getLoop() == L)
842     return true;
843 
844   return false;
845 }
846 
847 /// Iteratively perform simplification on a worklist of users
848 /// of the specified induction variable. Each successive simplification may push
849 /// more users which may themselves be candidates for simplification.
850 ///
851 /// This algorithm does not require IVUsers analysis. Instead, it simplifies
852 /// instructions in-place during analysis. Rather than rewriting induction
853 /// variables bottom-up from their users, it transforms a chain of IVUsers
854 /// top-down, updating the IR only when it encounters a clear optimization
855 /// opportunity.
856 ///
857 /// Once DisableIVRewrite is default, LSR will be the only client of IVUsers.
858 ///
859 void SimplifyIndvar::simplifyUsers(PHINode *CurrIV, IVVisitor *V) {
860   if (!SE->isSCEVable(CurrIV->getType()))
861     return;
862 
863   // Instructions processed by SimplifyIndvar for CurrIV.
864   SmallPtrSet<Instruction*,16> Simplified;
865 
866   // Use-def pairs if IV users waiting to be processed for CurrIV.
867   SmallVector<std::pair<Instruction*, Instruction*>, 8> SimpleIVUsers;
868 
869   // Push users of the current LoopPhi. In rare cases, pushIVUsers may be
870   // called multiple times for the same LoopPhi. This is the proper thing to
871   // do for loop header phis that use each other.
872   pushIVUsers(CurrIV, L, Simplified, SimpleIVUsers);
873 
874   while (!SimpleIVUsers.empty()) {
875     std::pair<Instruction*, Instruction*> UseOper =
876       SimpleIVUsers.pop_back_val();
877     Instruction *UseInst = UseOper.first;
878 
879     // If a user of the IndVar is trivially dead, we prefer just to mark it dead
880     // rather than try to do some complex analysis or transformation (such as
881     // widening) basing on it.
882     // TODO: Propagate TLI and pass it here to handle more cases.
883     if (isInstructionTriviallyDead(UseInst, /* TLI */ nullptr)) {
884       DeadInsts.emplace_back(UseInst);
885       continue;
886     }
887 
888     // Bypass back edges to avoid extra work.
889     if (UseInst == CurrIV) continue;
890 
891     // Try to replace UseInst with a loop invariant before any other
892     // simplifications.
893     if (replaceIVUserWithLoopInvariant(UseInst))
894       continue;
895 
896     Instruction *IVOperand = UseOper.second;
897     for (unsigned N = 0; IVOperand; ++N) {
898       assert(N <= Simplified.size() && "runaway iteration");
899 
900       Value *NewOper = foldIVUser(UseInst, IVOperand);
901       if (!NewOper)
902         break; // done folding
903       IVOperand = dyn_cast<Instruction>(NewOper);
904     }
905     if (!IVOperand)
906       continue;
907 
908     if (eliminateIVUser(UseInst, IVOperand)) {
909       pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
910       continue;
911     }
912 
913     if (BinaryOperator *BO = dyn_cast<BinaryOperator>(UseInst)) {
914       if ((isa<OverflowingBinaryOperator>(BO) &&
915            strengthenOverflowingOperation(BO, IVOperand)) ||
916           (isa<ShlOperator>(BO) && strengthenRightShift(BO, IVOperand))) {
917         // re-queue uses of the now modified binary operator and fall
918         // through to the checks that remain.
919         pushIVUsers(IVOperand, L, Simplified, SimpleIVUsers);
920       }
921     }
922 
923     CastInst *Cast = dyn_cast<CastInst>(UseInst);
924     if (V && Cast) {
925       V->visitCast(Cast);
926       continue;
927     }
928     if (isSimpleIVUser(UseInst, L, SE)) {
929       pushIVUsers(UseInst, L, Simplified, SimpleIVUsers);
930     }
931   }
932 }
933 
934 namespace llvm {
935 
936 void IVVisitor::anchor() { }
937 
938 /// Simplify instructions that use this induction variable
939 /// by using ScalarEvolution to analyze the IV's recurrence.
940 bool simplifyUsersOfIV(PHINode *CurrIV, ScalarEvolution *SE, DominatorTree *DT,
941                        LoopInfo *LI, const TargetTransformInfo *TTI,
942                        SmallVectorImpl<WeakTrackingVH> &Dead,
943                        SCEVExpander &Rewriter, IVVisitor *V) {
944   SimplifyIndvar SIV(LI->getLoopFor(CurrIV->getParent()), SE, DT, LI, TTI,
945                      Rewriter, Dead);
946   SIV.simplifyUsers(CurrIV, V);
947   return SIV.hasChanged();
948 }
949 
950 /// Simplify users of induction variables within this
951 /// loop. This does not actually change or add IVs.
952 bool simplifyLoopIVs(Loop *L, ScalarEvolution *SE, DominatorTree *DT,
953                      LoopInfo *LI, const TargetTransformInfo *TTI,
954                      SmallVectorImpl<WeakTrackingVH> &Dead) {
955   SCEVExpander Rewriter(*SE, SE->getDataLayout(), "indvars");
956 #ifndef NDEBUG
957   Rewriter.setDebugType(DEBUG_TYPE);
958 #endif
959   bool Changed = false;
960   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
961     Changed |=
962         simplifyUsersOfIV(cast<PHINode>(I), SE, DT, LI, TTI, Dead, Rewriter);
963   }
964   return Changed;
965 }
966 
967 } // namespace llvm
968 
969 //===----------------------------------------------------------------------===//
970 // Widen Induction Variables - Extend the width of an IV to cover its
971 // widest uses.
972 //===----------------------------------------------------------------------===//
973 
974 class WidenIV {
975   // Parameters
976   PHINode *OrigPhi;
977   Type *WideType;
978 
979   // Context
980   LoopInfo        *LI;
981   Loop            *L;
982   ScalarEvolution *SE;
983   DominatorTree   *DT;
984 
985   // Does the module have any calls to the llvm.experimental.guard intrinsic
986   // at all? If not we can avoid scanning instructions looking for guards.
987   bool HasGuards;
988 
989   bool UsePostIncrementRanges;
990 
991   // Statistics
992   unsigned NumElimExt = 0;
993   unsigned NumWidened = 0;
994 
995   // Result
996   PHINode *WidePhi = nullptr;
997   Instruction *WideInc = nullptr;
998   const SCEV *WideIncExpr = nullptr;
999   SmallVectorImpl<WeakTrackingVH> &DeadInsts;
1000 
1001   SmallPtrSet<Instruction *,16> Widened;
1002 
1003   enum ExtendKind { ZeroExtended, SignExtended, Unknown };
1004 
1005   // A map tracking the kind of extension used to widen each narrow IV
1006   // and narrow IV user.
1007   // Key: pointer to a narrow IV or IV user.
1008   // Value: the kind of extension used to widen this Instruction.
1009   DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
1010 
1011   using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
1012 
1013   // A map with control-dependent ranges for post increment IV uses. The key is
1014   // a pair of IV def and a use of this def denoting the context. The value is
1015   // a ConstantRange representing possible values of the def at the given
1016   // context.
1017   DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
1018 
1019   Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
1020                                               Instruction *UseI) {
1021     DefUserPair Key(Def, UseI);
1022     auto It = PostIncRangeInfos.find(Key);
1023     return It == PostIncRangeInfos.end()
1024                ? Optional<ConstantRange>(None)
1025                : Optional<ConstantRange>(It->second);
1026   }
1027 
1028   void calculatePostIncRanges(PHINode *OrigPhi);
1029   void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
1030 
1031   void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
1032     DefUserPair Key(Def, UseI);
1033     auto It = PostIncRangeInfos.find(Key);
1034     if (It == PostIncRangeInfos.end())
1035       PostIncRangeInfos.insert({Key, R});
1036     else
1037       It->second = R.intersectWith(It->second);
1038   }
1039 
1040 public:
1041   /// Record a link in the Narrow IV def-use chain along with the WideIV that
1042   /// computes the same value as the Narrow IV def.  This avoids caching Use*
1043   /// pointers.
1044   struct NarrowIVDefUse {
1045     Instruction *NarrowDef = nullptr;
1046     Instruction *NarrowUse = nullptr;
1047     Instruction *WideDef = nullptr;
1048 
1049     // True if the narrow def is never negative.  Tracking this information lets
1050     // us use a sign extension instead of a zero extension or vice versa, when
1051     // profitable and legal.
1052     bool NeverNegative = false;
1053 
1054     NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
1055                    bool NeverNegative)
1056         : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
1057           NeverNegative(NeverNegative) {}
1058   };
1059 
1060   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1061           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1062           bool HasGuards, bool UsePostIncrementRanges = true);
1063 
1064   PHINode *createWideIV(SCEVExpander &Rewriter);
1065 
1066   unsigned getNumElimExt() { return NumElimExt; };
1067   unsigned getNumWidened() { return NumWidened; };
1068 
1069 protected:
1070   Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
1071                           Instruction *Use);
1072 
1073   Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1074   Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1075                                      const SCEVAddRecExpr *WideAR);
1076   Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1077 
1078   ExtendKind getExtendKind(Instruction *I);
1079 
1080   using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1081 
1082   WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1083 
1084   WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1085 
1086   const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1087                               unsigned OpCode) const;
1088 
1089   Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
1090 
1091   bool widenLoopCompare(NarrowIVDefUse DU);
1092   bool widenWithVariantUse(NarrowIVDefUse DU);
1093 
1094   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1095 
1096 private:
1097   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
1098 };
1099 
1100 
1101 /// Determine the insertion point for this user. By default, insert immediately
1102 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
1103 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
1104 /// common dominator for the incoming blocks. A nullptr can be returned if no
1105 /// viable location is found: it may happen if User is a PHI and Def only comes
1106 /// to this PHI from unreachable blocks.
1107 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
1108                                           DominatorTree *DT, LoopInfo *LI) {
1109   PHINode *PHI = dyn_cast<PHINode>(User);
1110   if (!PHI)
1111     return User;
1112 
1113   Instruction *InsertPt = nullptr;
1114   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
1115     if (PHI->getIncomingValue(i) != Def)
1116       continue;
1117 
1118     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
1119 
1120     if (!DT->isReachableFromEntry(InsertBB))
1121       continue;
1122 
1123     if (!InsertPt) {
1124       InsertPt = InsertBB->getTerminator();
1125       continue;
1126     }
1127     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
1128     InsertPt = InsertBB->getTerminator();
1129   }
1130 
1131   // If we have skipped all inputs, it means that Def only comes to Phi from
1132   // unreachable blocks.
1133   if (!InsertPt)
1134     return nullptr;
1135 
1136   auto *DefI = dyn_cast<Instruction>(Def);
1137   if (!DefI)
1138     return InsertPt;
1139 
1140   assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
1141 
1142   auto *L = LI->getLoopFor(DefI->getParent());
1143   assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
1144 
1145   for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
1146     if (LI->getLoopFor(DTN->getBlock()) == L)
1147       return DTN->getBlock()->getTerminator();
1148 
1149   llvm_unreachable("DefI dominates InsertPt!");
1150 }
1151 
1152 WidenIV::WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
1153           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
1154           bool HasGuards, bool UsePostIncrementRanges)
1155       : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
1156         L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
1157         HasGuards(HasGuards), UsePostIncrementRanges(UsePostIncrementRanges),
1158         DeadInsts(DI) {
1159     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
1160     ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
1161 }
1162 
1163 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1164                                  bool IsSigned, Instruction *Use) {
1165   // Set the debug location and conservative insertion point.
1166   IRBuilder<> Builder(Use);
1167   // Hoist the insertion point into loop preheaders as far as possible.
1168   for (const Loop *L = LI->getLoopFor(Use->getParent());
1169        L && L->getLoopPreheader() && L->isLoopInvariant(NarrowOper);
1170        L = L->getParentLoop())
1171     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1172 
1173   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1174                     Builder.CreateZExt(NarrowOper, WideType);
1175 }
1176 
1177 /// Instantiate a wide operation to replace a narrow operation. This only needs
1178 /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1179 /// 0 for any operation we decide not to clone.
1180 Instruction *WidenIV::cloneIVUser(WidenIV::NarrowIVDefUse DU,
1181                                   const SCEVAddRecExpr *WideAR) {
1182   unsigned Opcode = DU.NarrowUse->getOpcode();
1183   switch (Opcode) {
1184   default:
1185     return nullptr;
1186   case Instruction::Add:
1187   case Instruction::Mul:
1188   case Instruction::UDiv:
1189   case Instruction::Sub:
1190     return cloneArithmeticIVUser(DU, WideAR);
1191 
1192   case Instruction::And:
1193   case Instruction::Or:
1194   case Instruction::Xor:
1195   case Instruction::Shl:
1196   case Instruction::LShr:
1197   case Instruction::AShr:
1198     return cloneBitwiseIVUser(DU);
1199   }
1200 }
1201 
1202 Instruction *WidenIV::cloneBitwiseIVUser(WidenIV::NarrowIVDefUse DU) {
1203   Instruction *NarrowUse = DU.NarrowUse;
1204   Instruction *NarrowDef = DU.NarrowDef;
1205   Instruction *WideDef = DU.WideDef;
1206 
1207   LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1208 
1209   // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1210   // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1211   // invariant and will be folded or hoisted. If it actually comes from a
1212   // widened IV, it should be removed during a future call to widenIVUse.
1213   bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1214   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1215                    ? WideDef
1216                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1217                                       IsSigned, NarrowUse);
1218   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1219                    ? WideDef
1220                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1221                                       IsSigned, NarrowUse);
1222 
1223   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1224   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1225                                         NarrowBO->getName());
1226   IRBuilder<> Builder(NarrowUse);
1227   Builder.Insert(WideBO);
1228   WideBO->copyIRFlags(NarrowBO);
1229   return WideBO;
1230 }
1231 
1232 Instruction *WidenIV::cloneArithmeticIVUser(WidenIV::NarrowIVDefUse DU,
1233                                             const SCEVAddRecExpr *WideAR) {
1234   Instruction *NarrowUse = DU.NarrowUse;
1235   Instruction *NarrowDef = DU.NarrowDef;
1236   Instruction *WideDef = DU.WideDef;
1237 
1238   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1239 
1240   unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1241 
1242   // We're trying to find X such that
1243   //
1244   //  Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1245   //
1246   // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1247   // and check using SCEV if any of them are correct.
1248 
1249   // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1250   // correct solution to X.
1251   auto GuessNonIVOperand = [&](bool SignExt) {
1252     const SCEV *WideLHS;
1253     const SCEV *WideRHS;
1254 
1255     auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1256       if (SignExt)
1257         return SE->getSignExtendExpr(S, Ty);
1258       return SE->getZeroExtendExpr(S, Ty);
1259     };
1260 
1261     if (IVOpIdx == 0) {
1262       WideLHS = SE->getSCEV(WideDef);
1263       const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1264       WideRHS = GetExtend(NarrowRHS, WideType);
1265     } else {
1266       const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1267       WideLHS = GetExtend(NarrowLHS, WideType);
1268       WideRHS = SE->getSCEV(WideDef);
1269     }
1270 
1271     // WideUse is "WideDef `op.wide` X" as described in the comment.
1272     const SCEV *WideUse =
1273       getSCEVByOpCode(WideLHS, WideRHS, NarrowUse->getOpcode());
1274 
1275     return WideUse == WideAR;
1276   };
1277 
1278   bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1279   if (!GuessNonIVOperand(SignExtend)) {
1280     SignExtend = !SignExtend;
1281     if (!GuessNonIVOperand(SignExtend))
1282       return nullptr;
1283   }
1284 
1285   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1286                    ? WideDef
1287                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1288                                       SignExtend, NarrowUse);
1289   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1290                    ? WideDef
1291                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1292                                       SignExtend, NarrowUse);
1293 
1294   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1295   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1296                                         NarrowBO->getName());
1297 
1298   IRBuilder<> Builder(NarrowUse);
1299   Builder.Insert(WideBO);
1300   WideBO->copyIRFlags(NarrowBO);
1301   return WideBO;
1302 }
1303 
1304 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1305   auto It = ExtendKindMap.find(I);
1306   assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1307   return It->second;
1308 }
1309 
1310 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1311                                      unsigned OpCode) const {
1312   switch (OpCode) {
1313   case Instruction::Add:
1314     return SE->getAddExpr(LHS, RHS);
1315   case Instruction::Sub:
1316     return SE->getMinusSCEV(LHS, RHS);
1317   case Instruction::Mul:
1318     return SE->getMulExpr(LHS, RHS);
1319   case Instruction::UDiv:
1320     return SE->getUDivExpr(LHS, RHS);
1321   default:
1322     llvm_unreachable("Unsupported opcode.");
1323   };
1324 }
1325 
1326 /// No-wrap operations can transfer sign extension of their result to their
1327 /// operands. Generate the SCEV value for the widened operation without
1328 /// actually modifying the IR yet. If the expression after extending the
1329 /// operands is an AddRec for this loop, return the AddRec and the kind of
1330 /// extension used.
1331 WidenIV::WidenedRecTy
1332 WidenIV::getExtendedOperandRecurrence(WidenIV::NarrowIVDefUse DU) {
1333   // Handle the common case of add<nsw/nuw>
1334   const unsigned OpCode = DU.NarrowUse->getOpcode();
1335   // Only Add/Sub/Mul instructions supported yet.
1336   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1337       OpCode != Instruction::Mul)
1338     return {nullptr, Unknown};
1339 
1340   // One operand (NarrowDef) has already been extended to WideDef. Now determine
1341   // if extending the other will lead to a recurrence.
1342   const unsigned ExtendOperIdx =
1343       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1344   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1345 
1346   const SCEV *ExtendOperExpr = nullptr;
1347   const OverflowingBinaryOperator *OBO =
1348     cast<OverflowingBinaryOperator>(DU.NarrowUse);
1349   ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1350   if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
1351     ExtendOperExpr = SE->getSignExtendExpr(
1352       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1353   else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
1354     ExtendOperExpr = SE->getZeroExtendExpr(
1355       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1356   else
1357     return {nullptr, Unknown};
1358 
1359   // When creating this SCEV expr, don't apply the current operations NSW or NUW
1360   // flags. This instruction may be guarded by control flow that the no-wrap
1361   // behavior depends on. Non-control-equivalent instructions can be mapped to
1362   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1363   // semantics to those operations.
1364   const SCEV *lhs = SE->getSCEV(DU.WideDef);
1365   const SCEV *rhs = ExtendOperExpr;
1366 
1367   // Let's swap operands to the initial order for the case of non-commutative
1368   // operations, like SUB. See PR21014.
1369   if (ExtendOperIdx == 0)
1370     std::swap(lhs, rhs);
1371   const SCEVAddRecExpr *AddRec =
1372       dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1373 
1374   if (!AddRec || AddRec->getLoop() != L)
1375     return {nullptr, Unknown};
1376 
1377   return {AddRec, ExtKind};
1378 }
1379 
1380 /// Is this instruction potentially interesting for further simplification after
1381 /// widening it's type? In other words, can the extend be safely hoisted out of
1382 /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1383 /// so, return the extended recurrence and the kind of extension used. Otherwise
1384 /// return {nullptr, Unknown}.
1385 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(WidenIV::NarrowIVDefUse DU) {
1386   if (!SE->isSCEVable(DU.NarrowUse->getType()))
1387     return {nullptr, Unknown};
1388 
1389   const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1390   if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1391       SE->getTypeSizeInBits(WideType)) {
1392     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1393     // index. So don't follow this use.
1394     return {nullptr, Unknown};
1395   }
1396 
1397   const SCEV *WideExpr;
1398   ExtendKind ExtKind;
1399   if (DU.NeverNegative) {
1400     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1401     if (isa<SCEVAddRecExpr>(WideExpr))
1402       ExtKind = SignExtended;
1403     else {
1404       WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1405       ExtKind = ZeroExtended;
1406     }
1407   } else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1408     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1409     ExtKind = SignExtended;
1410   } else {
1411     WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1412     ExtKind = ZeroExtended;
1413   }
1414   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1415   if (!AddRec || AddRec->getLoop() != L)
1416     return {nullptr, Unknown};
1417   return {AddRec, ExtKind};
1418 }
1419 
1420 /// This IV user cannot be widened. Replace this use of the original narrow IV
1421 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
1422 static void truncateIVUse(WidenIV::NarrowIVDefUse DU, DominatorTree *DT,
1423                           LoopInfo *LI) {
1424   auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1425   if (!InsertPt)
1426     return;
1427   LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1428                     << *DU.NarrowUse << "\n");
1429   IRBuilder<> Builder(InsertPt);
1430   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1431   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1432 }
1433 
1434 /// If the narrow use is a compare instruction, then widen the compare
1435 //  (and possibly the other operand).  The extend operation is hoisted into the
1436 // loop preheader as far as possible.
1437 bool WidenIV::widenLoopCompare(WidenIV::NarrowIVDefUse DU) {
1438   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1439   if (!Cmp)
1440     return false;
1441 
1442   // We can legally widen the comparison in the following two cases:
1443   //
1444   //  - The signedness of the IV extension and comparison match
1445   //
1446   //  - The narrow IV is always positive (and thus its sign extension is equal
1447   //    to its zero extension).  For instance, let's say we're zero extending
1448   //    %narrow for the following use
1449   //
1450   //      icmp slt i32 %narrow, %val   ... (A)
1451   //
1452   //    and %narrow is always positive.  Then
1453   //
1454   //      (A) == icmp slt i32 sext(%narrow), sext(%val)
1455   //          == icmp slt i32 zext(%narrow), sext(%val)
1456   bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1457   if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1458     return false;
1459 
1460   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1461   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1462   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1463   assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1464 
1465   // Widen the compare instruction.
1466   auto *InsertPt = getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI);
1467   if (!InsertPt)
1468     return false;
1469   IRBuilder<> Builder(InsertPt);
1470   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1471 
1472   // Widen the other operand of the compare, if necessary.
1473   if (CastWidth < IVWidth) {
1474     Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1475     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1476   }
1477   return true;
1478 }
1479 
1480 /// Find a point in code which dominates all given instructions. We can safely
1481 /// assume that, whatever fact we can prove at the found point, this fact is
1482 /// also true for each of the given instructions.
1483 static Instruction *findCommonDominator(ArrayRef<Instruction *> Instructions,
1484                                         DominatorTree &DT) {
1485   Instruction *CommonDom = nullptr;
1486   for (auto *Insn : Instructions)
1487     if (!CommonDom || DT.dominates(Insn, CommonDom))
1488       CommonDom = Insn;
1489     else if (!DT.dominates(CommonDom, Insn))
1490       // If there is no dominance relation, use common dominator.
1491       CommonDom =
1492           DT.findNearestCommonDominator(CommonDom->getParent(),
1493                                         Insn->getParent())->getTerminator();
1494   assert(CommonDom && "Common dominator not found?");
1495   return CommonDom;
1496 }
1497 
1498 // The widenIVUse avoids generating trunc by evaluating the use as AddRec, this
1499 // will not work when:
1500 //    1) SCEV traces back to an instruction inside the loop that SCEV can not
1501 // expand, eg. add %indvar, (load %addr)
1502 //    2) SCEV finds a loop variant, eg. add %indvar, %loopvariant
1503 // While SCEV fails to avoid trunc, we can still try to use instruction
1504 // combining approach to prove trunc is not required. This can be further
1505 // extended with other instruction combining checks, but for now we handle the
1506 // following case (sub can be "add" and "mul", "nsw + sext" can be "nus + zext")
1507 //
1508 // Src:
1509 //   %c = sub nsw %b, %indvar
1510 //   %d = sext %c to i64
1511 // Dst:
1512 //   %indvar.ext1 = sext %indvar to i64
1513 //   %m = sext %b to i64
1514 //   %d = sub nsw i64 %m, %indvar.ext1
1515 // Therefore, as long as the result of add/sub/mul is extended to wide type, no
1516 // trunc is required regardless of how %b is generated. This pattern is common
1517 // when calculating address in 64 bit architecture
1518 bool WidenIV::widenWithVariantUse(WidenIV::NarrowIVDefUse DU) {
1519   Instruction *NarrowUse = DU.NarrowUse;
1520   Instruction *NarrowDef = DU.NarrowDef;
1521   Instruction *WideDef = DU.WideDef;
1522 
1523   // Handle the common case of add<nsw/nuw>
1524   const unsigned OpCode = NarrowUse->getOpcode();
1525   // Only Add/Sub/Mul instructions are supported.
1526   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1527       OpCode != Instruction::Mul)
1528     return false;
1529 
1530   // The operand that is not defined by NarrowDef of DU. Let's call it the
1531   // other operand.
1532   assert((NarrowUse->getOperand(0) == NarrowDef ||
1533           NarrowUse->getOperand(1) == NarrowDef) &&
1534          "bad DU");
1535 
1536   const OverflowingBinaryOperator *OBO =
1537     cast<OverflowingBinaryOperator>(NarrowUse);
1538   ExtendKind ExtKind = getExtendKind(NarrowDef);
1539   bool CanSignExtend = ExtKind == SignExtended && OBO->hasNoSignedWrap();
1540   bool CanZeroExtend = ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap();
1541   auto AnotherOpExtKind = ExtKind;
1542 
1543   // Check that all uses are either:
1544   // - narrow def (in case of we are widening the IV increment);
1545   // - single-input LCSSA Phis;
1546   // - comparison of the chosen type;
1547   // - extend of the chosen type (raison d'etre).
1548   SmallVector<Instruction *, 4> ExtUsers;
1549   SmallVector<PHINode *, 4> LCSSAPhiUsers;
1550   SmallVector<ICmpInst *, 4> ICmpUsers;
1551   for (Use &U : NarrowUse->uses()) {
1552     Instruction *User = cast<Instruction>(U.getUser());
1553     if (User == NarrowDef)
1554       continue;
1555     if (!L->contains(User)) {
1556       auto *LCSSAPhi = cast<PHINode>(User);
1557       // Make sure there is only 1 input, so that we don't have to split
1558       // critical edges.
1559       if (LCSSAPhi->getNumOperands() != 1)
1560         return false;
1561       LCSSAPhiUsers.push_back(LCSSAPhi);
1562       continue;
1563     }
1564     if (auto *ICmp = dyn_cast<ICmpInst>(User)) {
1565       auto Pred = ICmp->getPredicate();
1566       // We have 3 types of predicates: signed, unsigned and equality
1567       // predicates. For equality, it's legal to widen icmp for either sign and
1568       // zero extend. For sign extend, we can also do so for signed predicates,
1569       // likeweise for zero extend we can widen icmp for unsigned predicates.
1570       if (ExtKind == ZeroExtended && ICmpInst::isSigned(Pred))
1571         return false;
1572       if (ExtKind == SignExtended && ICmpInst::isUnsigned(Pred))
1573         return false;
1574       ICmpUsers.push_back(ICmp);
1575       continue;
1576     }
1577     if (ExtKind == SignExtended)
1578       User = dyn_cast<SExtInst>(User);
1579     else
1580       User = dyn_cast<ZExtInst>(User);
1581     if (!User || User->getType() != WideType)
1582       return false;
1583     ExtUsers.push_back(User);
1584   }
1585   if (ExtUsers.empty()) {
1586     DeadInsts.emplace_back(NarrowUse);
1587     return true;
1588   }
1589 
1590   // We'll prove some facts that should be true in the context of ext users. If
1591   // there is no users, we are done now. If there are some, pick their common
1592   // dominator as context.
1593   const Instruction *CtxI = findCommonDominator(ExtUsers, *DT);
1594 
1595   if (!CanSignExtend && !CanZeroExtend) {
1596     // Because InstCombine turns 'sub nuw' to 'add' losing the no-wrap flag, we
1597     // will most likely not see it. Let's try to prove it.
1598     if (OpCode != Instruction::Add)
1599       return false;
1600     if (ExtKind != ZeroExtended)
1601       return false;
1602     const SCEV *LHS = SE->getSCEV(OBO->getOperand(0));
1603     const SCEV *RHS = SE->getSCEV(OBO->getOperand(1));
1604     // TODO: Support case for NarrowDef = NarrowUse->getOperand(1).
1605     if (NarrowUse->getOperand(0) != NarrowDef)
1606       return false;
1607     if (!SE->isKnownNegative(RHS))
1608       return false;
1609     bool ProvedSubNUW = SE->isKnownPredicateAt(ICmpInst::ICMP_UGE, LHS,
1610                                                SE->getNegativeSCEV(RHS), CtxI);
1611     if (!ProvedSubNUW)
1612       return false;
1613     // In fact, our 'add' is 'sub nuw'. We will need to widen the 2nd operand as
1614     // neg(zext(neg(op))), which is basically sext(op).
1615     AnotherOpExtKind = SignExtended;
1616   }
1617 
1618   // Verifying that Defining operand is an AddRec
1619   const SCEV *Op1 = SE->getSCEV(WideDef);
1620   const SCEVAddRecExpr *AddRecOp1 = dyn_cast<SCEVAddRecExpr>(Op1);
1621   if (!AddRecOp1 || AddRecOp1->getLoop() != L)
1622     return false;
1623 
1624   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1625 
1626   // Generating a widening use instruction.
1627   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1628                    ? WideDef
1629                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1630                                       AnotherOpExtKind, NarrowUse);
1631   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1632                    ? WideDef
1633                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1634                                       AnotherOpExtKind, NarrowUse);
1635 
1636   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1637   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1638                                         NarrowBO->getName());
1639   IRBuilder<> Builder(NarrowUse);
1640   Builder.Insert(WideBO);
1641   WideBO->copyIRFlags(NarrowBO);
1642   ExtendKindMap[NarrowUse] = ExtKind;
1643 
1644   for (Instruction *User : ExtUsers) {
1645     assert(User->getType() == WideType && "Checked before!");
1646     LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *User << " replaced by "
1647                       << *WideBO << "\n");
1648     ++NumElimExt;
1649     User->replaceAllUsesWith(WideBO);
1650     DeadInsts.emplace_back(User);
1651   }
1652 
1653   for (PHINode *User : LCSSAPhiUsers) {
1654     assert(User->getNumOperands() == 1 && "Checked before!");
1655     Builder.SetInsertPoint(User);
1656     auto *WidePN =
1657         Builder.CreatePHI(WideBO->getType(), 1, User->getName() + ".wide");
1658     BasicBlock *LoopExitingBlock = User->getParent()->getSinglePredecessor();
1659     assert(LoopExitingBlock && L->contains(LoopExitingBlock) &&
1660            "Not a LCSSA Phi?");
1661     WidePN->addIncoming(WideBO, LoopExitingBlock);
1662     Builder.SetInsertPoint(&*User->getParent()->getFirstInsertionPt());
1663     auto *TruncPN = Builder.CreateTrunc(WidePN, User->getType());
1664     User->replaceAllUsesWith(TruncPN);
1665     DeadInsts.emplace_back(User);
1666   }
1667 
1668   for (ICmpInst *User : ICmpUsers) {
1669     Builder.SetInsertPoint(User);
1670     auto ExtendedOp = [&](Value * V)->Value * {
1671       if (V == NarrowUse)
1672         return WideBO;
1673       if (ExtKind == ZeroExtended)
1674         return Builder.CreateZExt(V, WideBO->getType());
1675       else
1676         return Builder.CreateSExt(V, WideBO->getType());
1677     };
1678     auto Pred = User->getPredicate();
1679     auto *LHS = ExtendedOp(User->getOperand(0));
1680     auto *RHS = ExtendedOp(User->getOperand(1));
1681     auto *WideCmp =
1682         Builder.CreateICmp(Pred, LHS, RHS, User->getName() + ".wide");
1683     User->replaceAllUsesWith(WideCmp);
1684     DeadInsts.emplace_back(User);
1685   }
1686 
1687   return true;
1688 }
1689 
1690 /// Determine whether an individual user of the narrow IV can be widened. If so,
1691 /// return the wide clone of the user.
1692 Instruction *WidenIV::widenIVUse(WidenIV::NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1693   assert(ExtendKindMap.count(DU.NarrowDef) &&
1694          "Should already know the kind of extension used to widen NarrowDef");
1695 
1696   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1697   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1698     if (LI->getLoopFor(UsePhi->getParent()) != L) {
1699       // For LCSSA phis, sink the truncate outside the loop.
1700       // After SimplifyCFG most loop exit targets have a single predecessor.
1701       // Otherwise fall back to a truncate within the loop.
1702       if (UsePhi->getNumOperands() != 1)
1703         truncateIVUse(DU, DT, LI);
1704       else {
1705         // Widening the PHI requires us to insert a trunc.  The logical place
1706         // for this trunc is in the same BB as the PHI.  This is not possible if
1707         // the BB is terminated by a catchswitch.
1708         if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1709           return nullptr;
1710 
1711         PHINode *WidePhi =
1712           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1713                           UsePhi);
1714         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1715         IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1716         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1717         UsePhi->replaceAllUsesWith(Trunc);
1718         DeadInsts.emplace_back(UsePhi);
1719         LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1720                           << *WidePhi << "\n");
1721       }
1722       return nullptr;
1723     }
1724   }
1725 
1726   // This narrow use can be widened by a sext if it's non-negative or its narrow
1727   // def was widended by a sext. Same for zext.
1728   auto canWidenBySExt = [&]() {
1729     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1730   };
1731   auto canWidenByZExt = [&]() {
1732     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1733   };
1734 
1735   // Our raison d'etre! Eliminate sign and zero extension.
1736   if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1737       (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1738     Value *NewDef = DU.WideDef;
1739     if (DU.NarrowUse->getType() != WideType) {
1740       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1741       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1742       if (CastWidth < IVWidth) {
1743         // The cast isn't as wide as the IV, so insert a Trunc.
1744         IRBuilder<> Builder(DU.NarrowUse);
1745         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1746       }
1747       else {
1748         // A wider extend was hidden behind a narrower one. This may induce
1749         // another round of IV widening in which the intermediate IV becomes
1750         // dead. It should be very rare.
1751         LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1752                           << " not wide enough to subsume " << *DU.NarrowUse
1753                           << "\n");
1754         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1755         NewDef = DU.NarrowUse;
1756       }
1757     }
1758     if (NewDef != DU.NarrowUse) {
1759       LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1760                         << " replaced by " << *DU.WideDef << "\n");
1761       ++NumElimExt;
1762       DU.NarrowUse->replaceAllUsesWith(NewDef);
1763       DeadInsts.emplace_back(DU.NarrowUse);
1764     }
1765     // Now that the extend is gone, we want to expose it's uses for potential
1766     // further simplification. We don't need to directly inform SimplifyIVUsers
1767     // of the new users, because their parent IV will be processed later as a
1768     // new loop phi. If we preserved IVUsers analysis, we would also want to
1769     // push the uses of WideDef here.
1770 
1771     // No further widening is needed. The deceased [sz]ext had done it for us.
1772     return nullptr;
1773   }
1774 
1775   // Does this user itself evaluate to a recurrence after widening?
1776   WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1777   if (!WideAddRec.first)
1778     WideAddRec = getWideRecurrence(DU);
1779 
1780   assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
1781   if (!WideAddRec.first) {
1782     // If use is a loop condition, try to promote the condition instead of
1783     // truncating the IV first.
1784     if (widenLoopCompare(DU))
1785       return nullptr;
1786 
1787     // We are here about to generate a truncate instruction that may hurt
1788     // performance because the scalar evolution expression computed earlier
1789     // in WideAddRec.first does not indicate a polynomial induction expression.
1790     // In that case, look at the operands of the use instruction to determine
1791     // if we can still widen the use instead of truncating its operand.
1792     if (widenWithVariantUse(DU))
1793       return nullptr;
1794 
1795     // This user does not evaluate to a recurrence after widening, so don't
1796     // follow it. Instead insert a Trunc to kill off the original use,
1797     // eventually isolating the original narrow IV so it can be removed.
1798     truncateIVUse(DU, DT, LI);
1799     return nullptr;
1800   }
1801   // Assume block terminators cannot evaluate to a recurrence. We can't to
1802   // insert a Trunc after a terminator if there happens to be a critical edge.
1803   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1804          "SCEV is not expected to evaluate a block terminator");
1805 
1806   // Reuse the IV increment that SCEVExpander created as long as it dominates
1807   // NarrowUse.
1808   Instruction *WideUse = nullptr;
1809   if (WideAddRec.first == WideIncExpr &&
1810       Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1811     WideUse = WideInc;
1812   else {
1813     WideUse = cloneIVUser(DU, WideAddRec.first);
1814     if (!WideUse)
1815       return nullptr;
1816   }
1817   // Evaluation of WideAddRec ensured that the narrow expression could be
1818   // extended outside the loop without overflow. This suggests that the wide use
1819   // evaluates to the same expression as the extended narrow use, but doesn't
1820   // absolutely guarantee it. Hence the following failsafe check. In rare cases
1821   // where it fails, we simply throw away the newly created wide use.
1822   if (WideAddRec.first != SE->getSCEV(WideUse)) {
1823     LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1824                       << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1825                       << "\n");
1826     DeadInsts.emplace_back(WideUse);
1827     return nullptr;
1828   }
1829 
1830   // if we reached this point then we are going to replace
1831   // DU.NarrowUse with WideUse. Reattach DbgValue then.
1832   replaceAllDbgUsesWith(*DU.NarrowUse, *WideUse, *WideUse, *DT);
1833 
1834   ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1835   // Returning WideUse pushes it on the worklist.
1836   return WideUse;
1837 }
1838 
1839 /// Add eligible users of NarrowDef to NarrowIVUsers.
1840 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1841   const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1842   bool NonNegativeDef =
1843       SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1844                            SE->getZero(NarrowSCEV->getType()));
1845   for (User *U : NarrowDef->users()) {
1846     Instruction *NarrowUser = cast<Instruction>(U);
1847 
1848     // Handle data flow merges and bizarre phi cycles.
1849     if (!Widened.insert(NarrowUser).second)
1850       continue;
1851 
1852     bool NonNegativeUse = false;
1853     if (!NonNegativeDef) {
1854       // We might have a control-dependent range information for this context.
1855       if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1856         NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1857     }
1858 
1859     NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1860                                NonNegativeDef || NonNegativeUse);
1861   }
1862 }
1863 
1864 /// Process a single induction variable. First use the SCEVExpander to create a
1865 /// wide induction variable that evaluates to the same recurrence as the
1866 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1867 /// def-use chain. After widenIVUse has processed all interesting IV users, the
1868 /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1869 ///
1870 /// It would be simpler to delete uses as they are processed, but we must avoid
1871 /// invalidating SCEV expressions.
1872 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1873   // Is this phi an induction variable?
1874   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1875   if (!AddRec)
1876     return nullptr;
1877 
1878   // Widen the induction variable expression.
1879   const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1880                                ? SE->getSignExtendExpr(AddRec, WideType)
1881                                : SE->getZeroExtendExpr(AddRec, WideType);
1882 
1883   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1884          "Expect the new IV expression to preserve its type");
1885 
1886   // Can the IV be extended outside the loop without overflow?
1887   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1888   if (!AddRec || AddRec->getLoop() != L)
1889     return nullptr;
1890 
1891   // An AddRec must have loop-invariant operands. Since this AddRec is
1892   // materialized by a loop header phi, the expression cannot have any post-loop
1893   // operands, so they must dominate the loop header.
1894   assert(
1895       SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1896       SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1897       "Loop header phi recurrence inputs do not dominate the loop");
1898 
1899   // Iterate over IV uses (including transitive ones) looking for IV increments
1900   // of the form 'add nsw %iv, <const>'. For each increment and each use of
1901   // the increment calculate control-dependent range information basing on
1902   // dominating conditions inside of the loop (e.g. a range check inside of the
1903   // loop). Calculated ranges are stored in PostIncRangeInfos map.
1904   //
1905   // Control-dependent range information is later used to prove that a narrow
1906   // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1907   // this on demand because when pushNarrowIVUsers needs this information some
1908   // of the dominating conditions might be already widened.
1909   if (UsePostIncrementRanges)
1910     calculatePostIncRanges(OrigPhi);
1911 
1912   // The rewriter provides a value for the desired IV expression. This may
1913   // either find an existing phi or materialize a new one. Either way, we
1914   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1915   // of the phi-SCC dominates the loop entry.
1916   Instruction *InsertPt = &*L->getHeader()->getFirstInsertionPt();
1917   Value *ExpandInst = Rewriter.expandCodeFor(AddRec, WideType, InsertPt);
1918   // If the wide phi is not a phi node, for example a cast node, like bitcast,
1919   // inttoptr, ptrtoint, just skip for now.
1920   if (!(WidePhi = dyn_cast<PHINode>(ExpandInst))) {
1921     // if the cast node is an inserted instruction without any user, we should
1922     // remove it to make sure the pass don't touch the function as we can not
1923     // wide the phi.
1924     if (ExpandInst->hasNUses(0) &&
1925         Rewriter.isInsertedInstruction(cast<Instruction>(ExpandInst)))
1926       DeadInsts.emplace_back(ExpandInst);
1927     return nullptr;
1928   }
1929 
1930   // Remembering the WideIV increment generated by SCEVExpander allows
1931   // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1932   // employ a general reuse mechanism because the call above is the only call to
1933   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1934   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1935     WideInc =
1936       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1937     WideIncExpr = SE->getSCEV(WideInc);
1938     // Propagate the debug location associated with the original loop increment
1939     // to the new (widened) increment.
1940     auto *OrigInc =
1941       cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1942     WideInc->setDebugLoc(OrigInc->getDebugLoc());
1943   }
1944 
1945   LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1946   ++NumWidened;
1947 
1948   // Traverse the def-use chain using a worklist starting at the original IV.
1949   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1950 
1951   Widened.insert(OrigPhi);
1952   pushNarrowIVUsers(OrigPhi, WidePhi);
1953 
1954   while (!NarrowIVUsers.empty()) {
1955     WidenIV::NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1956 
1957     // Process a def-use edge. This may replace the use, so don't hold a
1958     // use_iterator across it.
1959     Instruction *WideUse = widenIVUse(DU, Rewriter);
1960 
1961     // Follow all def-use edges from the previous narrow use.
1962     if (WideUse)
1963       pushNarrowIVUsers(DU.NarrowUse, WideUse);
1964 
1965     // widenIVUse may have removed the def-use edge.
1966     if (DU.NarrowDef->use_empty())
1967       DeadInsts.emplace_back(DU.NarrowDef);
1968   }
1969 
1970   // Attach any debug information to the new PHI.
1971   replaceAllDbgUsesWith(*OrigPhi, *WidePhi, *WidePhi, *DT);
1972 
1973   return WidePhi;
1974 }
1975 
1976 /// Calculates control-dependent range for the given def at the given context
1977 /// by looking at dominating conditions inside of the loop
1978 void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
1979                                     Instruction *NarrowUser) {
1980   using namespace llvm::PatternMatch;
1981 
1982   Value *NarrowDefLHS;
1983   const APInt *NarrowDefRHS;
1984   if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
1985                                  m_APInt(NarrowDefRHS))) ||
1986       !NarrowDefRHS->isNonNegative())
1987     return;
1988 
1989   auto UpdateRangeFromCondition = [&] (Value *Condition,
1990                                        bool TrueDest) {
1991     CmpInst::Predicate Pred;
1992     Value *CmpRHS;
1993     if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
1994                                  m_Value(CmpRHS))))
1995       return;
1996 
1997     CmpInst::Predicate P =
1998             TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
1999 
2000     auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
2001     auto CmpConstrainedLHSRange =
2002             ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
2003     auto NarrowDefRange = CmpConstrainedLHSRange.addWithNoWrap(
2004         *NarrowDefRHS, OverflowingBinaryOperator::NoSignedWrap);
2005 
2006     updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
2007   };
2008 
2009   auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
2010     if (!HasGuards)
2011       return;
2012 
2013     for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
2014                                      Ctx->getParent()->rend())) {
2015       Value *C = nullptr;
2016       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
2017         UpdateRangeFromCondition(C, /*TrueDest=*/true);
2018     }
2019   };
2020 
2021   UpdateRangeFromGuards(NarrowUser);
2022 
2023   BasicBlock *NarrowUserBB = NarrowUser->getParent();
2024   // If NarrowUserBB is statically unreachable asking dominator queries may
2025   // yield surprising results. (e.g. the block may not have a dom tree node)
2026   if (!DT->isReachableFromEntry(NarrowUserBB))
2027     return;
2028 
2029   for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
2030        L->contains(DTB->getBlock());
2031        DTB = DTB->getIDom()) {
2032     auto *BB = DTB->getBlock();
2033     auto *TI = BB->getTerminator();
2034     UpdateRangeFromGuards(TI);
2035 
2036     auto *BI = dyn_cast<BranchInst>(TI);
2037     if (!BI || !BI->isConditional())
2038       continue;
2039 
2040     auto *TrueSuccessor = BI->getSuccessor(0);
2041     auto *FalseSuccessor = BI->getSuccessor(1);
2042 
2043     auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
2044       return BBE.isSingleEdge() &&
2045              DT->dominates(BBE, NarrowUser->getParent());
2046     };
2047 
2048     if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
2049       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
2050 
2051     if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
2052       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
2053   }
2054 }
2055 
2056 /// Calculates PostIncRangeInfos map for the given IV
2057 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
2058   SmallPtrSet<Instruction *, 16> Visited;
2059   SmallVector<Instruction *, 6> Worklist;
2060   Worklist.push_back(OrigPhi);
2061   Visited.insert(OrigPhi);
2062 
2063   while (!Worklist.empty()) {
2064     Instruction *NarrowDef = Worklist.pop_back_val();
2065 
2066     for (Use &U : NarrowDef->uses()) {
2067       auto *NarrowUser = cast<Instruction>(U.getUser());
2068 
2069       // Don't go looking outside the current loop.
2070       auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
2071       if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
2072         continue;
2073 
2074       if (!Visited.insert(NarrowUser).second)
2075         continue;
2076 
2077       Worklist.push_back(NarrowUser);
2078 
2079       calculatePostIncRange(NarrowDef, NarrowUser);
2080     }
2081   }
2082 }
2083 
2084 PHINode *llvm::createWideIV(const WideIVInfo &WI,
2085     LoopInfo *LI, ScalarEvolution *SE, SCEVExpander &Rewriter,
2086     DominatorTree *DT, SmallVectorImpl<WeakTrackingVH> &DeadInsts,
2087     unsigned &NumElimExt, unsigned &NumWidened,
2088     bool HasGuards, bool UsePostIncrementRanges) {
2089   WidenIV Widener(WI, LI, SE, DT, DeadInsts, HasGuards, UsePostIncrementRanges);
2090   PHINode *WidePHI = Widener.createWideIV(Rewriter);
2091   NumElimExt = Widener.getNumElimExt();
2092   NumWidened = Widener.getNumWidened();
2093   return WidePHI;
2094 }
2095