xref: /llvm-project/llvm/lib/Transforms/Scalar/IndVarSimplify.cpp (revision 51690c4f52a35e1008eaeb4e90a121fa3a6dc647)
1 //===- IndVarSimplify.cpp - Induction Variable Elimination ----------------===//
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 transformation analyzes and transforms the induction variables (and
11 // computations derived from them) into simpler forms suitable for subsequent
12 // analysis and transformation.
13 //
14 // If the trip count of a loop is computable, this pass also makes the following
15 // changes:
16 //   1. The exit condition for the loop is canonicalized to compare the
17 //      induction value against the exit value.  This turns loops like:
18 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
19 //   2. Any use outside of the loop of an expression derived from the indvar
20 //      is changed to compute the derived value outside of the loop, eliminating
21 //      the dependence on the exit value of the induction variable.  If the only
22 //      purpose of the loop is to compute the exit value of some derived
23 //      expression, this transformation will make the loop dead.
24 //
25 //===----------------------------------------------------------------------===//
26 
27 #include "llvm/Transforms/Scalar/IndVarSimplify.h"
28 #include "llvm/ADT/APFloat.h"
29 #include "llvm/ADT/APInt.h"
30 #include "llvm/ADT/ArrayRef.h"
31 #include "llvm/ADT/DenseMap.h"
32 #include "llvm/ADT/None.h"
33 #include "llvm/ADT/Optional.h"
34 #include "llvm/ADT/STLExtras.h"
35 #include "llvm/ADT/SmallPtrSet.h"
36 #include "llvm/ADT/SmallVector.h"
37 #include "llvm/ADT/Statistic.h"
38 #include "llvm/ADT/iterator_range.h"
39 #include "llvm/Analysis/LoopInfo.h"
40 #include "llvm/Analysis/LoopPass.h"
41 #include "llvm/Analysis/ScalarEvolution.h"
42 #include "llvm/Analysis/ScalarEvolutionExpander.h"
43 #include "llvm/Analysis/ScalarEvolutionExpressions.h"
44 #include "llvm/Analysis/TargetLibraryInfo.h"
45 #include "llvm/Analysis/TargetTransformInfo.h"
46 #include "llvm/Transforms/Utils/Local.h"
47 #include "llvm/IR/BasicBlock.h"
48 #include "llvm/IR/Constant.h"
49 #include "llvm/IR/ConstantRange.h"
50 #include "llvm/IR/Constants.h"
51 #include "llvm/IR/DataLayout.h"
52 #include "llvm/IR/DerivedTypes.h"
53 #include "llvm/IR/Dominators.h"
54 #include "llvm/IR/Function.h"
55 #include "llvm/IR/IRBuilder.h"
56 #include "llvm/IR/InstrTypes.h"
57 #include "llvm/IR/Instruction.h"
58 #include "llvm/IR/Instructions.h"
59 #include "llvm/IR/IntrinsicInst.h"
60 #include "llvm/IR/Intrinsics.h"
61 #include "llvm/IR/Module.h"
62 #include "llvm/IR/Operator.h"
63 #include "llvm/IR/PassManager.h"
64 #include "llvm/IR/PatternMatch.h"
65 #include "llvm/IR/Type.h"
66 #include "llvm/IR/Use.h"
67 #include "llvm/IR/User.h"
68 #include "llvm/IR/Value.h"
69 #include "llvm/IR/ValueHandle.h"
70 #include "llvm/Pass.h"
71 #include "llvm/Support/Casting.h"
72 #include "llvm/Support/CommandLine.h"
73 #include "llvm/Support/Compiler.h"
74 #include "llvm/Support/Debug.h"
75 #include "llvm/Support/ErrorHandling.h"
76 #include "llvm/Support/MathExtras.h"
77 #include "llvm/Support/raw_ostream.h"
78 #include "llvm/Transforms/Scalar.h"
79 #include "llvm/Transforms/Scalar/LoopPassManager.h"
80 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
81 #include "llvm/Transforms/Utils/LoopUtils.h"
82 #include "llvm/Transforms/Utils/SimplifyIndVar.h"
83 #include <cassert>
84 #include <cstdint>
85 #include <utility>
86 
87 using namespace llvm;
88 
89 #define DEBUG_TYPE "indvars"
90 
91 STATISTIC(NumWidened     , "Number of indvars widened");
92 STATISTIC(NumReplaced    , "Number of exit values replaced");
93 STATISTIC(NumLFTR        , "Number of loop exit tests replaced");
94 STATISTIC(NumElimExt     , "Number of IV sign/zero extends eliminated");
95 STATISTIC(NumElimIV      , "Number of congruent IVs eliminated");
96 
97 // Trip count verification can be enabled by default under NDEBUG if we
98 // implement a strong expression equivalence checker in SCEV. Until then, we
99 // use the verify-indvars flag, which may assert in some cases.
100 static cl::opt<bool> VerifyIndvars(
101   "verify-indvars", cl::Hidden,
102   cl::desc("Verify the ScalarEvolution result after running indvars"));
103 
104 enum ReplaceExitVal { NeverRepl, OnlyCheapRepl, AlwaysRepl };
105 
106 static cl::opt<ReplaceExitVal> ReplaceExitValue(
107     "replexitval", cl::Hidden, cl::init(OnlyCheapRepl),
108     cl::desc("Choose the strategy to replace exit value in IndVarSimplify"),
109     cl::values(clEnumValN(NeverRepl, "never", "never replace exit value"),
110                clEnumValN(OnlyCheapRepl, "cheap",
111                           "only replace exit value when the cost is cheap"),
112                clEnumValN(AlwaysRepl, "always",
113                           "always replace exit value whenever possible")));
114 
115 static cl::opt<bool> UsePostIncrementRanges(
116   "indvars-post-increment-ranges", cl::Hidden,
117   cl::desc("Use post increment control-dependent ranges in IndVarSimplify"),
118   cl::init(true));
119 
120 static cl::opt<bool>
121 DisableLFTR("disable-lftr", cl::Hidden, cl::init(false),
122             cl::desc("Disable Linear Function Test Replace optimization"));
123 
124 namespace {
125 
126 struct RewritePhi;
127 
128 class IndVarSimplify {
129   LoopInfo *LI;
130   ScalarEvolution *SE;
131   DominatorTree *DT;
132   const DataLayout &DL;
133   TargetLibraryInfo *TLI;
134   const TargetTransformInfo *TTI;
135 
136   SmallVector<WeakTrackingVH, 16> DeadInsts;
137   bool Changed = false;
138 
139 #ifndef NDEBUG
140   bool isValidRewrite(Value *FromVal, Value *ToVal);
141 #endif
142 
143   void handleFloatingPointIV(Loop *L, PHINode *PH);
144   void rewriteNonIntegerIVs(Loop *L);
145 
146   void simplifyAndExtend(Loop *L, SCEVExpander &Rewriter, LoopInfo *LI);
147 
148   bool canLoopBeDeleted(Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet);
149   void rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
150   void rewriteFirstIterationLoopExitValues(Loop *L);
151 
152   Value *linearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
153                                    PHINode *IndVar, SCEVExpander &Rewriter);
154 
155   void sinkUnusedInvariants(Loop *L);
156 
157 public:
158   IndVarSimplify(LoopInfo *LI, ScalarEvolution *SE, DominatorTree *DT,
159                  const DataLayout &DL, TargetLibraryInfo *TLI,
160                  TargetTransformInfo *TTI)
161       : LI(LI), SE(SE), DT(DT), DL(DL), TLI(TLI), TTI(TTI) {}
162 
163   bool run(Loop *L);
164 };
165 
166 } // end anonymous namespace
167 
168 #ifndef NDEBUG
169 /// Return true if the SCEV expansion generated by the rewriter can replace the
170 /// original value. SCEV guarantees that it produces the same value, but the way
171 /// it is produced may be illegal IR.
172 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
173   // If an SCEV expression subsumed multiple pointers, its expansion could
174   // reassociate the GEP changing the base pointer. This is illegal because the
175   // final address produced by a GEP chain must be inbounds relative to its
176   // underlying object. Otherwise basic alias analysis, among other things,
177   // could fail in a dangerous way. Specifically, we want to make sure that SCEV
178   // does not convert gep Base, (&p[n] - &p[0]) into gep &p[n], Base - &p[0].
179   //
180   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
181   // because it understands lcssa phis while SCEV does not.
182   Value *FromPtr = FromVal;
183   Value *ToPtr = ToVal;
184   if (auto *GEP = dyn_cast<GEPOperator>(FromVal)) {
185     FromPtr = GEP->getPointerOperand();
186   }
187   if (auto *GEP = dyn_cast<GEPOperator>(ToVal)) {
188     ToPtr = GEP->getPointerOperand();
189   }
190   if (FromPtr != FromVal || ToPtr != ToVal) {
191     // Quickly check the common case
192     if (FromPtr == ToPtr)
193       return true;
194 
195     // SCEV may have rewritten an expression that produces the GEP's pointer
196     // operand. That's ok as long as the pointer operand has the same base
197     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
198     // base of a recurrence. This handles the case in which SCEV expansion
199     // converts a pointer type recurrence into a nonrecurrent pointer base
200     // indexed by an integer recurrence.
201 
202     // If the GEP base pointer is a vector of pointers, abort.
203     if (!FromPtr->getType()->isPointerTy() || !ToPtr->getType()->isPointerTy())
204       return false;
205 
206     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
207     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
208     if (FromBase == ToBase)
209       return true;
210 
211     LLVM_DEBUG(dbgs() << "INDVARS: GEP rewrite bail out " << *FromBase
212                       << " != " << *ToBase << "\n");
213 
214     return false;
215   }
216   return true;
217 }
218 #endif
219 
220 /// Determine the insertion point for this user. By default, insert immediately
221 /// before the user. SCEVExpander or LICM will hoist loop invariants out of the
222 /// loop. For PHI nodes, there may be multiple uses, so compute the nearest
223 /// common dominator for the incoming blocks.
224 static Instruction *getInsertPointForUses(Instruction *User, Value *Def,
225                                           DominatorTree *DT, LoopInfo *LI) {
226   PHINode *PHI = dyn_cast<PHINode>(User);
227   if (!PHI)
228     return User;
229 
230   Instruction *InsertPt = nullptr;
231   for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i) {
232     if (PHI->getIncomingValue(i) != Def)
233       continue;
234 
235     BasicBlock *InsertBB = PHI->getIncomingBlock(i);
236     if (!InsertPt) {
237       InsertPt = InsertBB->getTerminator();
238       continue;
239     }
240     InsertBB = DT->findNearestCommonDominator(InsertPt->getParent(), InsertBB);
241     InsertPt = InsertBB->getTerminator();
242   }
243   assert(InsertPt && "Missing phi operand");
244 
245   auto *DefI = dyn_cast<Instruction>(Def);
246   if (!DefI)
247     return InsertPt;
248 
249   assert(DT->dominates(DefI, InsertPt) && "def does not dominate all uses");
250 
251   auto *L = LI->getLoopFor(DefI->getParent());
252   assert(!L || L->contains(LI->getLoopFor(InsertPt->getParent())));
253 
254   for (auto *DTN = (*DT)[InsertPt->getParent()]; DTN; DTN = DTN->getIDom())
255     if (LI->getLoopFor(DTN->getBlock()) == L)
256       return DTN->getBlock()->getTerminator();
257 
258   llvm_unreachable("DefI dominates InsertPt!");
259 }
260 
261 //===----------------------------------------------------------------------===//
262 // rewriteNonIntegerIVs and helpers. Prefer integer IVs.
263 //===----------------------------------------------------------------------===//
264 
265 /// Convert APF to an integer, if possible.
266 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
267   bool isExact = false;
268   // See if we can convert this to an int64_t
269   uint64_t UIntVal;
270   if (APF.convertToInteger(makeMutableArrayRef(UIntVal), 64, true,
271                            APFloat::rmTowardZero, &isExact) != APFloat::opOK ||
272       !isExact)
273     return false;
274   IntVal = UIntVal;
275   return true;
276 }
277 
278 /// If the loop has floating induction variable then insert corresponding
279 /// integer induction variable if possible.
280 /// For example,
281 /// for(double i = 0; i < 10000; ++i)
282 ///   bar(i)
283 /// is converted into
284 /// for(int i = 0; i < 10000; ++i)
285 ///   bar((double)i);
286 void IndVarSimplify::handleFloatingPointIV(Loop *L, PHINode *PN) {
287   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
288   unsigned BackEdge     = IncomingEdge^1;
289 
290   // Check incoming value.
291   auto *InitValueVal = dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
292 
293   int64_t InitValue;
294   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
295     return;
296 
297   // Check IV increment. Reject this PN if increment operation is not
298   // an add or increment value can not be represented by an integer.
299   auto *Incr = dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
300   if (Incr == nullptr || Incr->getOpcode() != Instruction::FAdd) return;
301 
302   // If this is not an add of the PHI with a constantfp, or if the constant fp
303   // is not an integer, bail out.
304   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
305   int64_t IncValue;
306   if (IncValueVal == nullptr || Incr->getOperand(0) != PN ||
307       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
308     return;
309 
310   // Check Incr uses. One user is PN and the other user is an exit condition
311   // used by the conditional terminator.
312   Value::user_iterator IncrUse = Incr->user_begin();
313   Instruction *U1 = cast<Instruction>(*IncrUse++);
314   if (IncrUse == Incr->user_end()) return;
315   Instruction *U2 = cast<Instruction>(*IncrUse++);
316   if (IncrUse != Incr->user_end()) return;
317 
318   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
319   // only used by a branch, we can't transform it.
320   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
321   if (!Compare)
322     Compare = dyn_cast<FCmpInst>(U2);
323   if (!Compare || !Compare->hasOneUse() ||
324       !isa<BranchInst>(Compare->user_back()))
325     return;
326 
327   BranchInst *TheBr = cast<BranchInst>(Compare->user_back());
328 
329   // We need to verify that the branch actually controls the iteration count
330   // of the loop.  If not, the new IV can overflow and no one will notice.
331   // The branch block must be in the loop and one of the successors must be out
332   // of the loop.
333   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
334   if (!L->contains(TheBr->getParent()) ||
335       (L->contains(TheBr->getSuccessor(0)) &&
336        L->contains(TheBr->getSuccessor(1))))
337     return;
338 
339   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
340   // transform it.
341   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
342   int64_t ExitValue;
343   if (ExitValueVal == nullptr ||
344       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
345     return;
346 
347   // Find new predicate for integer comparison.
348   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
349   switch (Compare->getPredicate()) {
350   default: return;  // Unknown comparison.
351   case CmpInst::FCMP_OEQ:
352   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
353   case CmpInst::FCMP_ONE:
354   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
355   case CmpInst::FCMP_OGT:
356   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
357   case CmpInst::FCMP_OGE:
358   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
359   case CmpInst::FCMP_OLT:
360   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
361   case CmpInst::FCMP_OLE:
362   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
363   }
364 
365   // We convert the floating point induction variable to a signed i32 value if
366   // we can.  This is only safe if the comparison will not overflow in a way
367   // that won't be trapped by the integer equivalent operations.  Check for this
368   // now.
369   // TODO: We could use i64 if it is native and the range requires it.
370 
371   // The start/stride/exit values must all fit in signed i32.
372   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
373     return;
374 
375   // If not actually striding (add x, 0.0), avoid touching the code.
376   if (IncValue == 0)
377     return;
378 
379   // Positive and negative strides have different safety conditions.
380   if (IncValue > 0) {
381     // If we have a positive stride, we require the init to be less than the
382     // exit value.
383     if (InitValue >= ExitValue)
384       return;
385 
386     uint32_t Range = uint32_t(ExitValue-InitValue);
387     // Check for infinite loop, either:
388     // while (i <= Exit) or until (i > Exit)
389     if (NewPred == CmpInst::ICMP_SLE || NewPred == CmpInst::ICMP_SGT) {
390       if (++Range == 0) return;  // Range overflows.
391     }
392 
393     unsigned Leftover = Range % uint32_t(IncValue);
394 
395     // If this is an equality comparison, we require that the strided value
396     // exactly land on the exit value, otherwise the IV condition will wrap
397     // around and do things the fp IV wouldn't.
398     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
399         Leftover != 0)
400       return;
401 
402     // If the stride would wrap around the i32 before exiting, we can't
403     // transform the IV.
404     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
405       return;
406   } else {
407     // If we have a negative stride, we require the init to be greater than the
408     // exit value.
409     if (InitValue <= ExitValue)
410       return;
411 
412     uint32_t Range = uint32_t(InitValue-ExitValue);
413     // Check for infinite loop, either:
414     // while (i >= Exit) or until (i < Exit)
415     if (NewPred == CmpInst::ICMP_SGE || NewPred == CmpInst::ICMP_SLT) {
416       if (++Range == 0) return;  // Range overflows.
417     }
418 
419     unsigned Leftover = Range % uint32_t(-IncValue);
420 
421     // If this is an equality comparison, we require that the strided value
422     // exactly land on the exit value, otherwise the IV condition will wrap
423     // around and do things the fp IV wouldn't.
424     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
425         Leftover != 0)
426       return;
427 
428     // If the stride would wrap around the i32 before exiting, we can't
429     // transform the IV.
430     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
431       return;
432   }
433 
434   IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
435 
436   // Insert new integer induction variable.
437   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
438   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
439                       PN->getIncomingBlock(IncomingEdge));
440 
441   Value *NewAdd =
442     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
443                               Incr->getName()+".int", Incr);
444   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
445 
446   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
447                                       ConstantInt::get(Int32Ty, ExitValue),
448                                       Compare->getName());
449 
450   // In the following deletions, PN may become dead and may be deleted.
451   // Use a WeakTrackingVH to observe whether this happens.
452   WeakTrackingVH WeakPH = PN;
453 
454   // Delete the old floating point exit comparison.  The branch starts using the
455   // new comparison.
456   NewCompare->takeName(Compare);
457   Compare->replaceAllUsesWith(NewCompare);
458   RecursivelyDeleteTriviallyDeadInstructions(Compare, TLI);
459 
460   // Delete the old floating point increment.
461   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
462   RecursivelyDeleteTriviallyDeadInstructions(Incr, TLI);
463 
464   // If the FP induction variable still has uses, this is because something else
465   // in the loop uses its value.  In order to canonicalize the induction
466   // variable, we chose to eliminate the IV and rewrite it in terms of an
467   // int->fp cast.
468   //
469   // We give preference to sitofp over uitofp because it is faster on most
470   // platforms.
471   if (WeakPH) {
472     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
473                                  &*PN->getParent()->getFirstInsertionPt());
474     PN->replaceAllUsesWith(Conv);
475     RecursivelyDeleteTriviallyDeadInstructions(PN, TLI);
476   }
477   Changed = true;
478 }
479 
480 void IndVarSimplify::rewriteNonIntegerIVs(Loop *L) {
481   // First step.  Check to see if there are any floating-point recurrences.
482   // If there are, change them into integer recurrences, permitting analysis by
483   // the SCEV routines.
484   BasicBlock *Header = L->getHeader();
485 
486   SmallVector<WeakTrackingVH, 8> PHIs;
487   for (PHINode &PN : Header->phis())
488     PHIs.push_back(&PN);
489 
490   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
491     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
492       handleFloatingPointIV(L, PN);
493 
494   // If the loop previously had floating-point IV, ScalarEvolution
495   // may not have been able to compute a trip count. Now that we've done some
496   // re-writing, the trip count may be computable.
497   if (Changed)
498     SE->forgetLoop(L);
499 }
500 
501 namespace {
502 
503 // Collect information about PHI nodes which can be transformed in
504 // rewriteLoopExitValues.
505 struct RewritePhi {
506   PHINode *PN;
507 
508   // Ith incoming value.
509   unsigned Ith;
510 
511   // Exit value after expansion.
512   Value *Val;
513 
514   // High Cost when expansion.
515   bool HighCost;
516 
517   RewritePhi(PHINode *P, unsigned I, Value *V, bool H)
518       : PN(P), Ith(I), Val(V), HighCost(H) {}
519 };
520 
521 } // end anonymous namespace
522 
523 //===----------------------------------------------------------------------===//
524 // rewriteLoopExitValues - Optimize IV users outside the loop.
525 // As a side effect, reduces the amount of IV processing within the loop.
526 //===----------------------------------------------------------------------===//
527 
528 /// Check to see if this loop has a computable loop-invariant execution count.
529 /// If so, this means that we can compute the final value of any expressions
530 /// that are recurrent in the loop, and substitute the exit values from the loop
531 /// into any instructions outside of the loop that use the final values of the
532 /// current expressions.
533 ///
534 /// This is mostly redundant with the regular IndVarSimplify activities that
535 /// happen later, except that it's more powerful in some cases, because it's
536 /// able to brute-force evaluate arbitrary instructions as long as they have
537 /// constant operands at the beginning of the loop.
538 void IndVarSimplify::rewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
539   // Check a pre-condition.
540   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
541          "Indvars did not preserve LCSSA!");
542 
543   SmallVector<BasicBlock*, 8> ExitBlocks;
544   L->getUniqueExitBlocks(ExitBlocks);
545 
546   SmallVector<RewritePhi, 8> RewritePhiSet;
547   // Find all values that are computed inside the loop, but used outside of it.
548   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
549   // the exit blocks of the loop to find them.
550   for (BasicBlock *ExitBB : ExitBlocks) {
551     // If there are no PHI nodes in this exit block, then no values defined
552     // inside the loop are used on this path, skip it.
553     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
554     if (!PN) continue;
555 
556     unsigned NumPreds = PN->getNumIncomingValues();
557 
558     // Iterate over all of the PHI nodes.
559     BasicBlock::iterator BBI = ExitBB->begin();
560     while ((PN = dyn_cast<PHINode>(BBI++))) {
561       if (PN->use_empty())
562         continue; // dead use, don't replace it
563 
564       if (!SE->isSCEVable(PN->getType()))
565         continue;
566 
567       // It's necessary to tell ScalarEvolution about this explicitly so that
568       // it can walk the def-use list and forget all SCEVs, as it may not be
569       // watching the PHI itself. Once the new exit value is in place, there
570       // may not be a def-use connection between the loop and every instruction
571       // which got a SCEVAddRecExpr for that loop.
572       SE->forgetValue(PN);
573 
574       // Iterate over all of the values in all the PHI nodes.
575       for (unsigned i = 0; i != NumPreds; ++i) {
576         // If the value being merged in is not integer or is not defined
577         // in the loop, skip it.
578         Value *InVal = PN->getIncomingValue(i);
579         if (!isa<Instruction>(InVal))
580           continue;
581 
582         // If this pred is for a subloop, not L itself, skip it.
583         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
584           continue; // The Block is in a subloop, skip it.
585 
586         // Check that InVal is defined in the loop.
587         Instruction *Inst = cast<Instruction>(InVal);
588         if (!L->contains(Inst))
589           continue;
590 
591         // Okay, this instruction has a user outside of the current loop
592         // and varies predictably *inside* the loop.  Evaluate the value it
593         // contains when the loop exits, if possible.
594         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
595         if (!SE->isLoopInvariant(ExitValue, L) ||
596             !isSafeToExpand(ExitValue, *SE))
597           continue;
598 
599         // Computing the value outside of the loop brings no benefit if :
600         //  - it is definitely used inside the loop in a way which can not be
601         //    optimized away.
602         //  - no use outside of the loop can take advantage of hoisting the
603         //    computation out of the loop
604         if (ExitValue->getSCEVType()>=scMulExpr) {
605           unsigned NumHardInternalUses = 0;
606           unsigned NumSoftExternalUses = 0;
607           unsigned NumUses = 0;
608           for (auto IB = Inst->user_begin(), IE = Inst->user_end();
609                IB != IE && NumUses <= 6; ++IB) {
610             Instruction *UseInstr = cast<Instruction>(*IB);
611             unsigned Opc = UseInstr->getOpcode();
612             NumUses++;
613             if (L->contains(UseInstr)) {
614               if (Opc == Instruction::Call)
615                 NumHardInternalUses++;
616             } else {
617               if (Opc == Instruction::PHI) {
618                 // Do not count the Phi as a use. LCSSA may have inserted
619                 // plenty of trivial ones.
620                 NumUses--;
621                 for (auto PB = UseInstr->user_begin(),
622                           PE = UseInstr->user_end();
623                      PB != PE && NumUses <= 6; ++PB, ++NumUses) {
624                   unsigned PhiOpc = cast<Instruction>(*PB)->getOpcode();
625                   if (PhiOpc != Instruction::Call && PhiOpc != Instruction::Ret)
626                     NumSoftExternalUses++;
627                 }
628                 continue;
629               }
630               if (Opc != Instruction::Call && Opc != Instruction::Ret)
631                 NumSoftExternalUses++;
632             }
633           }
634           if (NumUses <= 6 && NumHardInternalUses && !NumSoftExternalUses)
635             continue;
636         }
637 
638         bool HighCost = Rewriter.isHighCostExpansion(ExitValue, L, Inst);
639         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
640 
641         LLVM_DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
642                           << '\n'
643                           << "  LoopVal = " << *Inst << "\n");
644 
645         assert(isValidRewrite(Inst, ExitVal) && "Must be!");
646 
647 #ifndef NDEBUG
648         // If we reuse an instruction from a loop which is neither L nor one of
649         // its containing loops, we end up breaking LCSSA form for this loop by
650         // creating a new use of its instruction.
651         if (auto *ExitInsn = dyn_cast<Instruction>(ExitVal))
652           if (auto *EVL = LI->getLoopFor(ExitInsn->getParent()))
653             if (EVL != L)
654               assert(EVL->contains(L) && "LCSSA breach detected!");
655 #endif
656 
657         // Collect all the candidate PHINodes to be rewritten.
658         RewritePhiSet.emplace_back(PN, i, ExitVal, HighCost);
659       }
660     }
661   }
662 
663   bool LoopCanBeDel = canLoopBeDeleted(L, RewritePhiSet);
664 
665   // Transformation.
666   for (const RewritePhi &Phi : RewritePhiSet) {
667     PHINode *PN = Phi.PN;
668     Value *ExitVal = Phi.Val;
669 
670     // Only do the rewrite when the ExitValue can be expanded cheaply.
671     // If LoopCanBeDel is true, rewrite exit value aggressively.
672     if (ReplaceExitValue == OnlyCheapRepl && !LoopCanBeDel && Phi.HighCost) {
673       DeadInsts.push_back(ExitVal);
674       continue;
675     }
676 
677     Changed = true;
678     ++NumReplaced;
679     Instruction *Inst = cast<Instruction>(PN->getIncomingValue(Phi.Ith));
680     PN->setIncomingValue(Phi.Ith, ExitVal);
681 
682     // If this instruction is dead now, delete it. Don't do it now to avoid
683     // invalidating iterators.
684     if (isInstructionTriviallyDead(Inst, TLI))
685       DeadInsts.push_back(Inst);
686 
687     // Replace PN with ExitVal if that is legal and does not break LCSSA.
688     if (PN->getNumIncomingValues() == 1 &&
689         LI->replacementPreservesLCSSAForm(PN, ExitVal)) {
690       PN->replaceAllUsesWith(ExitVal);
691       PN->eraseFromParent();
692     }
693   }
694 
695   // The insertion point instruction may have been deleted; clear it out
696   // so that the rewriter doesn't trip over it later.
697   Rewriter.clearInsertPoint();
698 }
699 
700 //===---------------------------------------------------------------------===//
701 // rewriteFirstIterationLoopExitValues: Rewrite loop exit values if we know
702 // they will exit at the first iteration.
703 //===---------------------------------------------------------------------===//
704 
705 /// Check to see if this loop has loop invariant conditions which lead to loop
706 /// exits. If so, we know that if the exit path is taken, it is at the first
707 /// loop iteration. This lets us predict exit values of PHI nodes that live in
708 /// loop header.
709 void IndVarSimplify::rewriteFirstIterationLoopExitValues(Loop *L) {
710   // Verify the input to the pass is already in LCSSA form.
711   assert(L->isLCSSAForm(*DT));
712 
713   SmallVector<BasicBlock *, 8> ExitBlocks;
714   L->getUniqueExitBlocks(ExitBlocks);
715   auto *LoopHeader = L->getHeader();
716   assert(LoopHeader && "Invalid loop");
717 
718   for (auto *ExitBB : ExitBlocks) {
719     // If there are no more PHI nodes in this exit block, then no more
720     // values defined inside the loop are used on this path.
721     for (PHINode &PN : ExitBB->phis()) {
722       for (unsigned IncomingValIdx = 0, E = PN.getNumIncomingValues();
723            IncomingValIdx != E; ++IncomingValIdx) {
724         auto *IncomingBB = PN.getIncomingBlock(IncomingValIdx);
725 
726         // We currently only support loop exits from loop header. If the
727         // incoming block is not loop header, we need to recursively check
728         // all conditions starting from loop header are loop invariants.
729         // Additional support might be added in the future.
730         if (IncomingBB != LoopHeader)
731           continue;
732 
733         // Get condition that leads to the exit path.
734         auto *TermInst = IncomingBB->getTerminator();
735 
736         Value *Cond = nullptr;
737         if (auto *BI = dyn_cast<BranchInst>(TermInst)) {
738           // Must be a conditional branch, otherwise the block
739           // should not be in the loop.
740           Cond = BI->getCondition();
741         } else if (auto *SI = dyn_cast<SwitchInst>(TermInst))
742           Cond = SI->getCondition();
743         else
744           continue;
745 
746         if (!L->isLoopInvariant(Cond))
747           continue;
748 
749         auto *ExitVal = dyn_cast<PHINode>(PN.getIncomingValue(IncomingValIdx));
750 
751         // Only deal with PHIs.
752         if (!ExitVal)
753           continue;
754 
755         // If ExitVal is a PHI on the loop header, then we know its
756         // value along this exit because the exit can only be taken
757         // on the first iteration.
758         auto *LoopPreheader = L->getLoopPreheader();
759         assert(LoopPreheader && "Invalid loop");
760         int PreheaderIdx = ExitVal->getBasicBlockIndex(LoopPreheader);
761         if (PreheaderIdx != -1) {
762           assert(ExitVal->getParent() == LoopHeader &&
763                  "ExitVal must be in loop header");
764           PN.setIncomingValue(IncomingValIdx,
765                               ExitVal->getIncomingValue(PreheaderIdx));
766         }
767       }
768     }
769   }
770 }
771 
772 /// Check whether it is possible to delete the loop after rewriting exit
773 /// value. If it is possible, ignore ReplaceExitValue and do rewriting
774 /// aggressively.
775 bool IndVarSimplify::canLoopBeDeleted(
776     Loop *L, SmallVector<RewritePhi, 8> &RewritePhiSet) {
777   BasicBlock *Preheader = L->getLoopPreheader();
778   // If there is no preheader, the loop will not be deleted.
779   if (!Preheader)
780     return false;
781 
782   // In LoopDeletion pass Loop can be deleted when ExitingBlocks.size() > 1.
783   // We obviate multiple ExitingBlocks case for simplicity.
784   // TODO: If we see testcase with multiple ExitingBlocks can be deleted
785   // after exit value rewriting, we can enhance the logic here.
786   SmallVector<BasicBlock *, 4> ExitingBlocks;
787   L->getExitingBlocks(ExitingBlocks);
788   SmallVector<BasicBlock *, 8> ExitBlocks;
789   L->getUniqueExitBlocks(ExitBlocks);
790   if (ExitBlocks.size() > 1 || ExitingBlocks.size() > 1)
791     return false;
792 
793   BasicBlock *ExitBlock = ExitBlocks[0];
794   BasicBlock::iterator BI = ExitBlock->begin();
795   while (PHINode *P = dyn_cast<PHINode>(BI)) {
796     Value *Incoming = P->getIncomingValueForBlock(ExitingBlocks[0]);
797 
798     // If the Incoming value of P is found in RewritePhiSet, we know it
799     // could be rewritten to use a loop invariant value in transformation
800     // phase later. Skip it in the loop invariant check below.
801     bool found = false;
802     for (const RewritePhi &Phi : RewritePhiSet) {
803       unsigned i = Phi.Ith;
804       if (Phi.PN == P && (Phi.PN)->getIncomingValue(i) == Incoming) {
805         found = true;
806         break;
807       }
808     }
809 
810     Instruction *I;
811     if (!found && (I = dyn_cast<Instruction>(Incoming)))
812       if (!L->hasLoopInvariantOperands(I))
813         return false;
814 
815     ++BI;
816   }
817 
818   for (auto *BB : L->blocks())
819     if (llvm::any_of(*BB, [](Instruction &I) {
820           return I.mayHaveSideEffects();
821         }))
822       return false;
823 
824   return true;
825 }
826 
827 //===----------------------------------------------------------------------===//
828 //  IV Widening - Extend the width of an IV to cover its widest uses.
829 //===----------------------------------------------------------------------===//
830 
831 namespace {
832 
833 // Collect information about induction variables that are used by sign/zero
834 // extend operations. This information is recorded by CollectExtend and provides
835 // the input to WidenIV.
836 struct WideIVInfo {
837   PHINode *NarrowIV = nullptr;
838 
839   // Widest integer type created [sz]ext
840   Type *WidestNativeType = nullptr;
841 
842   // Was a sext user seen before a zext?
843   bool IsSigned = false;
844 };
845 
846 } // end anonymous namespace
847 
848 /// Update information about the induction variable that is extended by this
849 /// sign or zero extend operation. This is used to determine the final width of
850 /// the IV before actually widening it.
851 static void visitIVCast(CastInst *Cast, WideIVInfo &WI, ScalarEvolution *SE,
852                         const TargetTransformInfo *TTI) {
853   bool IsSigned = Cast->getOpcode() == Instruction::SExt;
854   if (!IsSigned && Cast->getOpcode() != Instruction::ZExt)
855     return;
856 
857   Type *Ty = Cast->getType();
858   uint64_t Width = SE->getTypeSizeInBits(Ty);
859   if (!Cast->getModule()->getDataLayout().isLegalInteger(Width))
860     return;
861 
862   // Check that `Cast` actually extends the induction variable (we rely on this
863   // later).  This takes care of cases where `Cast` is extending a truncation of
864   // the narrow induction variable, and thus can end up being narrower than the
865   // "narrow" induction variable.
866   uint64_t NarrowIVWidth = SE->getTypeSizeInBits(WI.NarrowIV->getType());
867   if (NarrowIVWidth >= Width)
868     return;
869 
870   // Cast is either an sext or zext up to this point.
871   // We should not widen an indvar if arithmetics on the wider indvar are more
872   // expensive than those on the narrower indvar. We check only the cost of ADD
873   // because at least an ADD is required to increment the induction variable. We
874   // could compute more comprehensively the cost of all instructions on the
875   // induction variable when necessary.
876   if (TTI &&
877       TTI->getArithmeticInstrCost(Instruction::Add, Ty) >
878           TTI->getArithmeticInstrCost(Instruction::Add,
879                                       Cast->getOperand(0)->getType())) {
880     return;
881   }
882 
883   if (!WI.WidestNativeType) {
884     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
885     WI.IsSigned = IsSigned;
886     return;
887   }
888 
889   // We extend the IV to satisfy the sign of its first user, arbitrarily.
890   if (WI.IsSigned != IsSigned)
891     return;
892 
893   if (Width > SE->getTypeSizeInBits(WI.WidestNativeType))
894     WI.WidestNativeType = SE->getEffectiveSCEVType(Ty);
895 }
896 
897 namespace {
898 
899 /// Record a link in the Narrow IV def-use chain along with the WideIV that
900 /// computes the same value as the Narrow IV def.  This avoids caching Use*
901 /// pointers.
902 struct NarrowIVDefUse {
903   Instruction *NarrowDef = nullptr;
904   Instruction *NarrowUse = nullptr;
905   Instruction *WideDef = nullptr;
906 
907   // True if the narrow def is never negative.  Tracking this information lets
908   // us use a sign extension instead of a zero extension or vice versa, when
909   // profitable and legal.
910   bool NeverNegative = false;
911 
912   NarrowIVDefUse(Instruction *ND, Instruction *NU, Instruction *WD,
913                  bool NeverNegative)
914       : NarrowDef(ND), NarrowUse(NU), WideDef(WD),
915         NeverNegative(NeverNegative) {}
916 };
917 
918 /// The goal of this transform is to remove sign and zero extends without
919 /// creating any new induction variables. To do this, it creates a new phi of
920 /// the wider type and redirects all users, either removing extends or inserting
921 /// truncs whenever we stop propagating the type.
922 class WidenIV {
923   // Parameters
924   PHINode *OrigPhi;
925   Type *WideType;
926 
927   // Context
928   LoopInfo        *LI;
929   Loop            *L;
930   ScalarEvolution *SE;
931   DominatorTree   *DT;
932 
933   // Does the module have any calls to the llvm.experimental.guard intrinsic
934   // at all? If not we can avoid scanning instructions looking for guards.
935   bool HasGuards;
936 
937   // Result
938   PHINode *WidePhi = nullptr;
939   Instruction *WideInc = nullptr;
940   const SCEV *WideIncExpr = nullptr;
941   SmallVectorImpl<WeakTrackingVH> &DeadInsts;
942 
943   SmallPtrSet<Instruction *,16> Widened;
944   SmallVector<NarrowIVDefUse, 8> NarrowIVUsers;
945 
946   enum ExtendKind { ZeroExtended, SignExtended, Unknown };
947 
948   // A map tracking the kind of extension used to widen each narrow IV
949   // and narrow IV user.
950   // Key: pointer to a narrow IV or IV user.
951   // Value: the kind of extension used to widen this Instruction.
952   DenseMap<AssertingVH<Instruction>, ExtendKind> ExtendKindMap;
953 
954   using DefUserPair = std::pair<AssertingVH<Value>, AssertingVH<Instruction>>;
955 
956   // A map with control-dependent ranges for post increment IV uses. The key is
957   // a pair of IV def and a use of this def denoting the context. The value is
958   // a ConstantRange representing possible values of the def at the given
959   // context.
960   DenseMap<DefUserPair, ConstantRange> PostIncRangeInfos;
961 
962   Optional<ConstantRange> getPostIncRangeInfo(Value *Def,
963                                               Instruction *UseI) {
964     DefUserPair Key(Def, UseI);
965     auto It = PostIncRangeInfos.find(Key);
966     return It == PostIncRangeInfos.end()
967                ? Optional<ConstantRange>(None)
968                : Optional<ConstantRange>(It->second);
969   }
970 
971   void calculatePostIncRanges(PHINode *OrigPhi);
972   void calculatePostIncRange(Instruction *NarrowDef, Instruction *NarrowUser);
973 
974   void updatePostIncRangeInfo(Value *Def, Instruction *UseI, ConstantRange R) {
975     DefUserPair Key(Def, UseI);
976     auto It = PostIncRangeInfos.find(Key);
977     if (It == PostIncRangeInfos.end())
978       PostIncRangeInfos.insert({Key, R});
979     else
980       It->second = R.intersectWith(It->second);
981   }
982 
983 public:
984   WidenIV(const WideIVInfo &WI, LoopInfo *LInfo, ScalarEvolution *SEv,
985           DominatorTree *DTree, SmallVectorImpl<WeakTrackingVH> &DI,
986           bool HasGuards)
987       : OrigPhi(WI.NarrowIV), WideType(WI.WidestNativeType), LI(LInfo),
988         L(LI->getLoopFor(OrigPhi->getParent())), SE(SEv), DT(DTree),
989         HasGuards(HasGuards), DeadInsts(DI) {
990     assert(L->getHeader() == OrigPhi->getParent() && "Phi must be an IV");
991     ExtendKindMap[OrigPhi] = WI.IsSigned ? SignExtended : ZeroExtended;
992   }
993 
994   PHINode *createWideIV(SCEVExpander &Rewriter);
995 
996 protected:
997   Value *createExtendInst(Value *NarrowOper, Type *WideType, bool IsSigned,
998                           Instruction *Use);
999 
1000   Instruction *cloneIVUser(NarrowIVDefUse DU, const SCEVAddRecExpr *WideAR);
1001   Instruction *cloneArithmeticIVUser(NarrowIVDefUse DU,
1002                                      const SCEVAddRecExpr *WideAR);
1003   Instruction *cloneBitwiseIVUser(NarrowIVDefUse DU);
1004 
1005   ExtendKind getExtendKind(Instruction *I);
1006 
1007   using WidenedRecTy = std::pair<const SCEVAddRecExpr *, ExtendKind>;
1008 
1009   WidenedRecTy getWideRecurrence(NarrowIVDefUse DU);
1010 
1011   WidenedRecTy getExtendedOperandRecurrence(NarrowIVDefUse DU);
1012 
1013   const SCEV *getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1014                               unsigned OpCode) const;
1015 
1016   Instruction *widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter);
1017 
1018   bool widenLoopCompare(NarrowIVDefUse DU);
1019 
1020   void pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef);
1021 };
1022 
1023 } // end anonymous namespace
1024 
1025 /// Perform a quick domtree based check for loop invariance assuming that V is
1026 /// used within the loop. LoopInfo::isLoopInvariant() seems gratuitous for this
1027 /// purpose.
1028 static bool isLoopInvariant(Value *V, const Loop *L, const DominatorTree *DT) {
1029   Instruction *Inst = dyn_cast<Instruction>(V);
1030   if (!Inst)
1031     return true;
1032 
1033   return DT->properlyDominates(Inst->getParent(), L->getHeader());
1034 }
1035 
1036 Value *WidenIV::createExtendInst(Value *NarrowOper, Type *WideType,
1037                                  bool IsSigned, Instruction *Use) {
1038   // Set the debug location and conservative insertion point.
1039   IRBuilder<> Builder(Use);
1040   // Hoist the insertion point into loop preheaders as far as possible.
1041   for (const Loop *L = LI->getLoopFor(Use->getParent());
1042        L && L->getLoopPreheader() && isLoopInvariant(NarrowOper, L, DT);
1043        L = L->getParentLoop())
1044     Builder.SetInsertPoint(L->getLoopPreheader()->getTerminator());
1045 
1046   return IsSigned ? Builder.CreateSExt(NarrowOper, WideType) :
1047                     Builder.CreateZExt(NarrowOper, WideType);
1048 }
1049 
1050 /// Instantiate a wide operation to replace a narrow operation. This only needs
1051 /// to handle operations that can evaluation to SCEVAddRec. It can safely return
1052 /// 0 for any operation we decide not to clone.
1053 Instruction *WidenIV::cloneIVUser(NarrowIVDefUse DU,
1054                                   const SCEVAddRecExpr *WideAR) {
1055   unsigned Opcode = DU.NarrowUse->getOpcode();
1056   switch (Opcode) {
1057   default:
1058     return nullptr;
1059   case Instruction::Add:
1060   case Instruction::Mul:
1061   case Instruction::UDiv:
1062   case Instruction::Sub:
1063     return cloneArithmeticIVUser(DU, WideAR);
1064 
1065   case Instruction::And:
1066   case Instruction::Or:
1067   case Instruction::Xor:
1068   case Instruction::Shl:
1069   case Instruction::LShr:
1070   case Instruction::AShr:
1071     return cloneBitwiseIVUser(DU);
1072   }
1073 }
1074 
1075 Instruction *WidenIV::cloneBitwiseIVUser(NarrowIVDefUse DU) {
1076   Instruction *NarrowUse = DU.NarrowUse;
1077   Instruction *NarrowDef = DU.NarrowDef;
1078   Instruction *WideDef = DU.WideDef;
1079 
1080   LLVM_DEBUG(dbgs() << "Cloning bitwise IVUser: " << *NarrowUse << "\n");
1081 
1082   // Replace NarrowDef operands with WideDef. Otherwise, we don't know anything
1083   // about the narrow operand yet so must insert a [sz]ext. It is probably loop
1084   // invariant and will be folded or hoisted. If it actually comes from a
1085   // widened IV, it should be removed during a future call to widenIVUse.
1086   bool IsSigned = getExtendKind(NarrowDef) == SignExtended;
1087   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1088                    ? WideDef
1089                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1090                                       IsSigned, NarrowUse);
1091   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1092                    ? WideDef
1093                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1094                                       IsSigned, NarrowUse);
1095 
1096   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1097   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1098                                         NarrowBO->getName());
1099   IRBuilder<> Builder(NarrowUse);
1100   Builder.Insert(WideBO);
1101   WideBO->copyIRFlags(NarrowBO);
1102   return WideBO;
1103 }
1104 
1105 Instruction *WidenIV::cloneArithmeticIVUser(NarrowIVDefUse DU,
1106                                             const SCEVAddRecExpr *WideAR) {
1107   Instruction *NarrowUse = DU.NarrowUse;
1108   Instruction *NarrowDef = DU.NarrowDef;
1109   Instruction *WideDef = DU.WideDef;
1110 
1111   LLVM_DEBUG(dbgs() << "Cloning arithmetic IVUser: " << *NarrowUse << "\n");
1112 
1113   unsigned IVOpIdx = (NarrowUse->getOperand(0) == NarrowDef) ? 0 : 1;
1114 
1115   // We're trying to find X such that
1116   //
1117   //  Widen(NarrowDef `op` NonIVNarrowDef) == WideAR == WideDef `op.wide` X
1118   //
1119   // We guess two solutions to X, sext(NonIVNarrowDef) and zext(NonIVNarrowDef),
1120   // and check using SCEV if any of them are correct.
1121 
1122   // Returns true if extending NonIVNarrowDef according to `SignExt` is a
1123   // correct solution to X.
1124   auto GuessNonIVOperand = [&](bool SignExt) {
1125     const SCEV *WideLHS;
1126     const SCEV *WideRHS;
1127 
1128     auto GetExtend = [this, SignExt](const SCEV *S, Type *Ty) {
1129       if (SignExt)
1130         return SE->getSignExtendExpr(S, Ty);
1131       return SE->getZeroExtendExpr(S, Ty);
1132     };
1133 
1134     if (IVOpIdx == 0) {
1135       WideLHS = SE->getSCEV(WideDef);
1136       const SCEV *NarrowRHS = SE->getSCEV(NarrowUse->getOperand(1));
1137       WideRHS = GetExtend(NarrowRHS, WideType);
1138     } else {
1139       const SCEV *NarrowLHS = SE->getSCEV(NarrowUse->getOperand(0));
1140       WideLHS = GetExtend(NarrowLHS, WideType);
1141       WideRHS = SE->getSCEV(WideDef);
1142     }
1143 
1144     // WideUse is "WideDef `op.wide` X" as described in the comment.
1145     const SCEV *WideUse = nullptr;
1146 
1147     switch (NarrowUse->getOpcode()) {
1148     default:
1149       llvm_unreachable("No other possibility!");
1150 
1151     case Instruction::Add:
1152       WideUse = SE->getAddExpr(WideLHS, WideRHS);
1153       break;
1154 
1155     case Instruction::Mul:
1156       WideUse = SE->getMulExpr(WideLHS, WideRHS);
1157       break;
1158 
1159     case Instruction::UDiv:
1160       WideUse = SE->getUDivExpr(WideLHS, WideRHS);
1161       break;
1162 
1163     case Instruction::Sub:
1164       WideUse = SE->getMinusSCEV(WideLHS, WideRHS);
1165       break;
1166     }
1167 
1168     return WideUse == WideAR;
1169   };
1170 
1171   bool SignExtend = getExtendKind(NarrowDef) == SignExtended;
1172   if (!GuessNonIVOperand(SignExtend)) {
1173     SignExtend = !SignExtend;
1174     if (!GuessNonIVOperand(SignExtend))
1175       return nullptr;
1176   }
1177 
1178   Value *LHS = (NarrowUse->getOperand(0) == NarrowDef)
1179                    ? WideDef
1180                    : createExtendInst(NarrowUse->getOperand(0), WideType,
1181                                       SignExtend, NarrowUse);
1182   Value *RHS = (NarrowUse->getOperand(1) == NarrowDef)
1183                    ? WideDef
1184                    : createExtendInst(NarrowUse->getOperand(1), WideType,
1185                                       SignExtend, NarrowUse);
1186 
1187   auto *NarrowBO = cast<BinaryOperator>(NarrowUse);
1188   auto *WideBO = BinaryOperator::Create(NarrowBO->getOpcode(), LHS, RHS,
1189                                         NarrowBO->getName());
1190 
1191   IRBuilder<> Builder(NarrowUse);
1192   Builder.Insert(WideBO);
1193   WideBO->copyIRFlags(NarrowBO);
1194   return WideBO;
1195 }
1196 
1197 WidenIV::ExtendKind WidenIV::getExtendKind(Instruction *I) {
1198   auto It = ExtendKindMap.find(I);
1199   assert(It != ExtendKindMap.end() && "Instruction not yet extended!");
1200   return It->second;
1201 }
1202 
1203 const SCEV *WidenIV::getSCEVByOpCode(const SCEV *LHS, const SCEV *RHS,
1204                                      unsigned OpCode) const {
1205   if (OpCode == Instruction::Add)
1206     return SE->getAddExpr(LHS, RHS);
1207   if (OpCode == Instruction::Sub)
1208     return SE->getMinusSCEV(LHS, RHS);
1209   if (OpCode == Instruction::Mul)
1210     return SE->getMulExpr(LHS, RHS);
1211 
1212   llvm_unreachable("Unsupported opcode.");
1213 }
1214 
1215 /// No-wrap operations can transfer sign extension of their result to their
1216 /// operands. Generate the SCEV value for the widened operation without
1217 /// actually modifying the IR yet. If the expression after extending the
1218 /// operands is an AddRec for this loop, return the AddRec and the kind of
1219 /// extension used.
1220 WidenIV::WidenedRecTy WidenIV::getExtendedOperandRecurrence(NarrowIVDefUse DU) {
1221   // Handle the common case of add<nsw/nuw>
1222   const unsigned OpCode = DU.NarrowUse->getOpcode();
1223   // Only Add/Sub/Mul instructions supported yet.
1224   if (OpCode != Instruction::Add && OpCode != Instruction::Sub &&
1225       OpCode != Instruction::Mul)
1226     return {nullptr, Unknown};
1227 
1228   // One operand (NarrowDef) has already been extended to WideDef. Now determine
1229   // if extending the other will lead to a recurrence.
1230   const unsigned ExtendOperIdx =
1231       DU.NarrowUse->getOperand(0) == DU.NarrowDef ? 1 : 0;
1232   assert(DU.NarrowUse->getOperand(1-ExtendOperIdx) == DU.NarrowDef && "bad DU");
1233 
1234   const SCEV *ExtendOperExpr = nullptr;
1235   const OverflowingBinaryOperator *OBO =
1236     cast<OverflowingBinaryOperator>(DU.NarrowUse);
1237   ExtendKind ExtKind = getExtendKind(DU.NarrowDef);
1238   if (ExtKind == SignExtended && OBO->hasNoSignedWrap())
1239     ExtendOperExpr = SE->getSignExtendExpr(
1240       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1241   else if(ExtKind == ZeroExtended && OBO->hasNoUnsignedWrap())
1242     ExtendOperExpr = SE->getZeroExtendExpr(
1243       SE->getSCEV(DU.NarrowUse->getOperand(ExtendOperIdx)), WideType);
1244   else
1245     return {nullptr, Unknown};
1246 
1247   // When creating this SCEV expr, don't apply the current operations NSW or NUW
1248   // flags. This instruction may be guarded by control flow that the no-wrap
1249   // behavior depends on. Non-control-equivalent instructions can be mapped to
1250   // the same SCEV expression, and it would be incorrect to transfer NSW/NUW
1251   // semantics to those operations.
1252   const SCEV *lhs = SE->getSCEV(DU.WideDef);
1253   const SCEV *rhs = ExtendOperExpr;
1254 
1255   // Let's swap operands to the initial order for the case of non-commutative
1256   // operations, like SUB. See PR21014.
1257   if (ExtendOperIdx == 0)
1258     std::swap(lhs, rhs);
1259   const SCEVAddRecExpr *AddRec =
1260       dyn_cast<SCEVAddRecExpr>(getSCEVByOpCode(lhs, rhs, OpCode));
1261 
1262   if (!AddRec || AddRec->getLoop() != L)
1263     return {nullptr, Unknown};
1264 
1265   return {AddRec, ExtKind};
1266 }
1267 
1268 /// Is this instruction potentially interesting for further simplification after
1269 /// widening it's type? In other words, can the extend be safely hoisted out of
1270 /// the loop with SCEV reducing the value to a recurrence on the same loop. If
1271 /// so, return the extended recurrence and the kind of extension used. Otherwise
1272 /// return {nullptr, Unknown}.
1273 WidenIV::WidenedRecTy WidenIV::getWideRecurrence(NarrowIVDefUse DU) {
1274   if (!SE->isSCEVable(DU.NarrowUse->getType()))
1275     return {nullptr, Unknown};
1276 
1277   const SCEV *NarrowExpr = SE->getSCEV(DU.NarrowUse);
1278   if (SE->getTypeSizeInBits(NarrowExpr->getType()) >=
1279       SE->getTypeSizeInBits(WideType)) {
1280     // NarrowUse implicitly widens its operand. e.g. a gep with a narrow
1281     // index. So don't follow this use.
1282     return {nullptr, Unknown};
1283   }
1284 
1285   const SCEV *WideExpr;
1286   ExtendKind ExtKind;
1287   if (DU.NeverNegative) {
1288     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1289     if (isa<SCEVAddRecExpr>(WideExpr))
1290       ExtKind = SignExtended;
1291     else {
1292       WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1293       ExtKind = ZeroExtended;
1294     }
1295   } else if (getExtendKind(DU.NarrowDef) == SignExtended) {
1296     WideExpr = SE->getSignExtendExpr(NarrowExpr, WideType);
1297     ExtKind = SignExtended;
1298   } else {
1299     WideExpr = SE->getZeroExtendExpr(NarrowExpr, WideType);
1300     ExtKind = ZeroExtended;
1301   }
1302   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(WideExpr);
1303   if (!AddRec || AddRec->getLoop() != L)
1304     return {nullptr, Unknown};
1305   return {AddRec, ExtKind};
1306 }
1307 
1308 /// This IV user cannot be widen. Replace this use of the original narrow IV
1309 /// with a truncation of the new wide IV to isolate and eliminate the narrow IV.
1310 static void truncateIVUse(NarrowIVDefUse DU, DominatorTree *DT, LoopInfo *LI) {
1311   LLVM_DEBUG(dbgs() << "INDVARS: Truncate IV " << *DU.WideDef << " for user "
1312                     << *DU.NarrowUse << "\n");
1313   IRBuilder<> Builder(
1314       getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1315   Value *Trunc = Builder.CreateTrunc(DU.WideDef, DU.NarrowDef->getType());
1316   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, Trunc);
1317 }
1318 
1319 /// If the narrow use is a compare instruction, then widen the compare
1320 //  (and possibly the other operand).  The extend operation is hoisted into the
1321 // loop preheader as far as possible.
1322 bool WidenIV::widenLoopCompare(NarrowIVDefUse DU) {
1323   ICmpInst *Cmp = dyn_cast<ICmpInst>(DU.NarrowUse);
1324   if (!Cmp)
1325     return false;
1326 
1327   // We can legally widen the comparison in the following two cases:
1328   //
1329   //  - The signedness of the IV extension and comparison match
1330   //
1331   //  - The narrow IV is always positive (and thus its sign extension is equal
1332   //    to its zero extension).  For instance, let's say we're zero extending
1333   //    %narrow for the following use
1334   //
1335   //      icmp slt i32 %narrow, %val   ... (A)
1336   //
1337   //    and %narrow is always positive.  Then
1338   //
1339   //      (A) == icmp slt i32 sext(%narrow), sext(%val)
1340   //          == icmp slt i32 zext(%narrow), sext(%val)
1341   bool IsSigned = getExtendKind(DU.NarrowDef) == SignExtended;
1342   if (!(DU.NeverNegative || IsSigned == Cmp->isSigned()))
1343     return false;
1344 
1345   Value *Op = Cmp->getOperand(Cmp->getOperand(0) == DU.NarrowDef ? 1 : 0);
1346   unsigned CastWidth = SE->getTypeSizeInBits(Op->getType());
1347   unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1348   assert(CastWidth <= IVWidth && "Unexpected width while widening compare.");
1349 
1350   // Widen the compare instruction.
1351   IRBuilder<> Builder(
1352       getInsertPointForUses(DU.NarrowUse, DU.NarrowDef, DT, LI));
1353   DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1354 
1355   // Widen the other operand of the compare, if necessary.
1356   if (CastWidth < IVWidth) {
1357     Value *ExtOp = createExtendInst(Op, WideType, Cmp->isSigned(), Cmp);
1358     DU.NarrowUse->replaceUsesOfWith(Op, ExtOp);
1359   }
1360   return true;
1361 }
1362 
1363 /// Determine whether an individual user of the narrow IV can be widened. If so,
1364 /// return the wide clone of the user.
1365 Instruction *WidenIV::widenIVUse(NarrowIVDefUse DU, SCEVExpander &Rewriter) {
1366   assert(ExtendKindMap.count(DU.NarrowDef) &&
1367          "Should already know the kind of extension used to widen NarrowDef");
1368 
1369   // Stop traversing the def-use chain at inner-loop phis or post-loop phis.
1370   if (PHINode *UsePhi = dyn_cast<PHINode>(DU.NarrowUse)) {
1371     if (LI->getLoopFor(UsePhi->getParent()) != L) {
1372       // For LCSSA phis, sink the truncate outside the loop.
1373       // After SimplifyCFG most loop exit targets have a single predecessor.
1374       // Otherwise fall back to a truncate within the loop.
1375       if (UsePhi->getNumOperands() != 1)
1376         truncateIVUse(DU, DT, LI);
1377       else {
1378         // Widening the PHI requires us to insert a trunc.  The logical place
1379         // for this trunc is in the same BB as the PHI.  This is not possible if
1380         // the BB is terminated by a catchswitch.
1381         if (isa<CatchSwitchInst>(UsePhi->getParent()->getTerminator()))
1382           return nullptr;
1383 
1384         PHINode *WidePhi =
1385           PHINode::Create(DU.WideDef->getType(), 1, UsePhi->getName() + ".wide",
1386                           UsePhi);
1387         WidePhi->addIncoming(DU.WideDef, UsePhi->getIncomingBlock(0));
1388         IRBuilder<> Builder(&*WidePhi->getParent()->getFirstInsertionPt());
1389         Value *Trunc = Builder.CreateTrunc(WidePhi, DU.NarrowDef->getType());
1390         UsePhi->replaceAllUsesWith(Trunc);
1391         DeadInsts.emplace_back(UsePhi);
1392         LLVM_DEBUG(dbgs() << "INDVARS: Widen lcssa phi " << *UsePhi << " to "
1393                           << *WidePhi << "\n");
1394       }
1395       return nullptr;
1396     }
1397   }
1398 
1399   // This narrow use can be widened by a sext if it's non-negative or its narrow
1400   // def was widended by a sext. Same for zext.
1401   auto canWidenBySExt = [&]() {
1402     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == SignExtended;
1403   };
1404   auto canWidenByZExt = [&]() {
1405     return DU.NeverNegative || getExtendKind(DU.NarrowDef) == ZeroExtended;
1406   };
1407 
1408   // Our raison d'etre! Eliminate sign and zero extension.
1409   if ((isa<SExtInst>(DU.NarrowUse) && canWidenBySExt()) ||
1410       (isa<ZExtInst>(DU.NarrowUse) && canWidenByZExt())) {
1411     Value *NewDef = DU.WideDef;
1412     if (DU.NarrowUse->getType() != WideType) {
1413       unsigned CastWidth = SE->getTypeSizeInBits(DU.NarrowUse->getType());
1414       unsigned IVWidth = SE->getTypeSizeInBits(WideType);
1415       if (CastWidth < IVWidth) {
1416         // The cast isn't as wide as the IV, so insert a Trunc.
1417         IRBuilder<> Builder(DU.NarrowUse);
1418         NewDef = Builder.CreateTrunc(DU.WideDef, DU.NarrowUse->getType());
1419       }
1420       else {
1421         // A wider extend was hidden behind a narrower one. This may induce
1422         // another round of IV widening in which the intermediate IV becomes
1423         // dead. It should be very rare.
1424         LLVM_DEBUG(dbgs() << "INDVARS: New IV " << *WidePhi
1425                           << " not wide enough to subsume " << *DU.NarrowUse
1426                           << "\n");
1427         DU.NarrowUse->replaceUsesOfWith(DU.NarrowDef, DU.WideDef);
1428         NewDef = DU.NarrowUse;
1429       }
1430     }
1431     if (NewDef != DU.NarrowUse) {
1432       LLVM_DEBUG(dbgs() << "INDVARS: eliminating " << *DU.NarrowUse
1433                         << " replaced by " << *DU.WideDef << "\n");
1434       ++NumElimExt;
1435       DU.NarrowUse->replaceAllUsesWith(NewDef);
1436       DeadInsts.emplace_back(DU.NarrowUse);
1437     }
1438     // Now that the extend is gone, we want to expose it's uses for potential
1439     // further simplification. We don't need to directly inform SimplifyIVUsers
1440     // of the new users, because their parent IV will be processed later as a
1441     // new loop phi. If we preserved IVUsers analysis, we would also want to
1442     // push the uses of WideDef here.
1443 
1444     // No further widening is needed. The deceased [sz]ext had done it for us.
1445     return nullptr;
1446   }
1447 
1448   // Does this user itself evaluate to a recurrence after widening?
1449   WidenedRecTy WideAddRec = getExtendedOperandRecurrence(DU);
1450   if (!WideAddRec.first)
1451     WideAddRec = getWideRecurrence(DU);
1452 
1453   assert((WideAddRec.first == nullptr) == (WideAddRec.second == Unknown));
1454   if (!WideAddRec.first) {
1455     // If use is a loop condition, try to promote the condition instead of
1456     // truncating the IV first.
1457     if (widenLoopCompare(DU))
1458       return nullptr;
1459 
1460     // This user does not evaluate to a recurrence after widening, so don't
1461     // follow it. Instead insert a Trunc to kill off the original use,
1462     // eventually isolating the original narrow IV so it can be removed.
1463     truncateIVUse(DU, DT, LI);
1464     return nullptr;
1465   }
1466   // Assume block terminators cannot evaluate to a recurrence. We can't to
1467   // insert a Trunc after a terminator if there happens to be a critical edge.
1468   assert(DU.NarrowUse != DU.NarrowUse->getParent()->getTerminator() &&
1469          "SCEV is not expected to evaluate a block terminator");
1470 
1471   // Reuse the IV increment that SCEVExpander created as long as it dominates
1472   // NarrowUse.
1473   Instruction *WideUse = nullptr;
1474   if (WideAddRec.first == WideIncExpr &&
1475       Rewriter.hoistIVInc(WideInc, DU.NarrowUse))
1476     WideUse = WideInc;
1477   else {
1478     WideUse = cloneIVUser(DU, WideAddRec.first);
1479     if (!WideUse)
1480       return nullptr;
1481   }
1482   // Evaluation of WideAddRec ensured that the narrow expression could be
1483   // extended outside the loop without overflow. This suggests that the wide use
1484   // evaluates to the same expression as the extended narrow use, but doesn't
1485   // absolutely guarantee it. Hence the following failsafe check. In rare cases
1486   // where it fails, we simply throw away the newly created wide use.
1487   if (WideAddRec.first != SE->getSCEV(WideUse)) {
1488     LLVM_DEBUG(dbgs() << "Wide use expression mismatch: " << *WideUse << ": "
1489                       << *SE->getSCEV(WideUse) << " != " << *WideAddRec.first
1490                       << "\n");
1491     DeadInsts.emplace_back(WideUse);
1492     return nullptr;
1493   }
1494 
1495   ExtendKindMap[DU.NarrowUse] = WideAddRec.second;
1496   // Returning WideUse pushes it on the worklist.
1497   return WideUse;
1498 }
1499 
1500 /// Add eligible users of NarrowDef to NarrowIVUsers.
1501 void WidenIV::pushNarrowIVUsers(Instruction *NarrowDef, Instruction *WideDef) {
1502   const SCEV *NarrowSCEV = SE->getSCEV(NarrowDef);
1503   bool NonNegativeDef =
1504       SE->isKnownPredicate(ICmpInst::ICMP_SGE, NarrowSCEV,
1505                            SE->getConstant(NarrowSCEV->getType(), 0));
1506   for (User *U : NarrowDef->users()) {
1507     Instruction *NarrowUser = cast<Instruction>(U);
1508 
1509     // Handle data flow merges and bizarre phi cycles.
1510     if (!Widened.insert(NarrowUser).second)
1511       continue;
1512 
1513     bool NonNegativeUse = false;
1514     if (!NonNegativeDef) {
1515       // We might have a control-dependent range information for this context.
1516       if (auto RangeInfo = getPostIncRangeInfo(NarrowDef, NarrowUser))
1517         NonNegativeUse = RangeInfo->getSignedMin().isNonNegative();
1518     }
1519 
1520     NarrowIVUsers.emplace_back(NarrowDef, NarrowUser, WideDef,
1521                                NonNegativeDef || NonNegativeUse);
1522   }
1523 }
1524 
1525 /// Process a single induction variable. First use the SCEVExpander to create a
1526 /// wide induction variable that evaluates to the same recurrence as the
1527 /// original narrow IV. Then use a worklist to forward traverse the narrow IV's
1528 /// def-use chain. After widenIVUse has processed all interesting IV users, the
1529 /// narrow IV will be isolated for removal by DeleteDeadPHIs.
1530 ///
1531 /// It would be simpler to delete uses as they are processed, but we must avoid
1532 /// invalidating SCEV expressions.
1533 PHINode *WidenIV::createWideIV(SCEVExpander &Rewriter) {
1534   // Is this phi an induction variable?
1535   const SCEVAddRecExpr *AddRec = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(OrigPhi));
1536   if (!AddRec)
1537     return nullptr;
1538 
1539   // Widen the induction variable expression.
1540   const SCEV *WideIVExpr = getExtendKind(OrigPhi) == SignExtended
1541                                ? SE->getSignExtendExpr(AddRec, WideType)
1542                                : SE->getZeroExtendExpr(AddRec, WideType);
1543 
1544   assert(SE->getEffectiveSCEVType(WideIVExpr->getType()) == WideType &&
1545          "Expect the new IV expression to preserve its type");
1546 
1547   // Can the IV be extended outside the loop without overflow?
1548   AddRec = dyn_cast<SCEVAddRecExpr>(WideIVExpr);
1549   if (!AddRec || AddRec->getLoop() != L)
1550     return nullptr;
1551 
1552   // An AddRec must have loop-invariant operands. Since this AddRec is
1553   // materialized by a loop header phi, the expression cannot have any post-loop
1554   // operands, so they must dominate the loop header.
1555   assert(
1556       SE->properlyDominates(AddRec->getStart(), L->getHeader()) &&
1557       SE->properlyDominates(AddRec->getStepRecurrence(*SE), L->getHeader()) &&
1558       "Loop header phi recurrence inputs do not dominate the loop");
1559 
1560   // Iterate over IV uses (including transitive ones) looking for IV increments
1561   // of the form 'add nsw %iv, <const>'. For each increment and each use of
1562   // the increment calculate control-dependent range information basing on
1563   // dominating conditions inside of the loop (e.g. a range check inside of the
1564   // loop). Calculated ranges are stored in PostIncRangeInfos map.
1565   //
1566   // Control-dependent range information is later used to prove that a narrow
1567   // definition is not negative (see pushNarrowIVUsers). It's difficult to do
1568   // this on demand because when pushNarrowIVUsers needs this information some
1569   // of the dominating conditions might be already widened.
1570   if (UsePostIncrementRanges)
1571     calculatePostIncRanges(OrigPhi);
1572 
1573   // The rewriter provides a value for the desired IV expression. This may
1574   // either find an existing phi or materialize a new one. Either way, we
1575   // expect a well-formed cyclic phi-with-increments. i.e. any operand not part
1576   // of the phi-SCC dominates the loop entry.
1577   Instruction *InsertPt = &L->getHeader()->front();
1578   WidePhi = cast<PHINode>(Rewriter.expandCodeFor(AddRec, WideType, InsertPt));
1579 
1580   // Remembering the WideIV increment generated by SCEVExpander allows
1581   // widenIVUse to reuse it when widening the narrow IV's increment. We don't
1582   // employ a general reuse mechanism because the call above is the only call to
1583   // SCEVExpander. Henceforth, we produce 1-to-1 narrow to wide uses.
1584   if (BasicBlock *LatchBlock = L->getLoopLatch()) {
1585     WideInc =
1586       cast<Instruction>(WidePhi->getIncomingValueForBlock(LatchBlock));
1587     WideIncExpr = SE->getSCEV(WideInc);
1588     // Propagate the debug location associated with the original loop increment
1589     // to the new (widened) increment.
1590     auto *OrigInc =
1591       cast<Instruction>(OrigPhi->getIncomingValueForBlock(LatchBlock));
1592     WideInc->setDebugLoc(OrigInc->getDebugLoc());
1593   }
1594 
1595   LLVM_DEBUG(dbgs() << "Wide IV: " << *WidePhi << "\n");
1596   ++NumWidened;
1597 
1598   // Traverse the def-use chain using a worklist starting at the original IV.
1599   assert(Widened.empty() && NarrowIVUsers.empty() && "expect initial state" );
1600 
1601   Widened.insert(OrigPhi);
1602   pushNarrowIVUsers(OrigPhi, WidePhi);
1603 
1604   while (!NarrowIVUsers.empty()) {
1605     NarrowIVDefUse DU = NarrowIVUsers.pop_back_val();
1606 
1607     // Process a def-use edge. This may replace the use, so don't hold a
1608     // use_iterator across it.
1609     Instruction *WideUse = widenIVUse(DU, Rewriter);
1610 
1611     // Follow all def-use edges from the previous narrow use.
1612     if (WideUse)
1613       pushNarrowIVUsers(DU.NarrowUse, WideUse);
1614 
1615     // widenIVUse may have removed the def-use edge.
1616     if (DU.NarrowDef->use_empty())
1617       DeadInsts.emplace_back(DU.NarrowDef);
1618   }
1619 
1620   // Attach any debug information to the new PHI. Since OrigPhi and WidePHI
1621   // evaluate the same recurrence, we can just copy the debug info over.
1622   SmallVector<DbgValueInst *, 1> DbgValues;
1623   llvm::findDbgValues(DbgValues, OrigPhi);
1624   auto *MDPhi = MetadataAsValue::get(WidePhi->getContext(),
1625                                      ValueAsMetadata::get(WidePhi));
1626   for (auto &DbgValue : DbgValues)
1627     DbgValue->setOperand(0, MDPhi);
1628   return WidePhi;
1629 }
1630 
1631 /// Calculates control-dependent range for the given def at the given context
1632 /// by looking at dominating conditions inside of the loop
1633 void WidenIV::calculatePostIncRange(Instruction *NarrowDef,
1634                                     Instruction *NarrowUser) {
1635   using namespace llvm::PatternMatch;
1636 
1637   Value *NarrowDefLHS;
1638   const APInt *NarrowDefRHS;
1639   if (!match(NarrowDef, m_NSWAdd(m_Value(NarrowDefLHS),
1640                                  m_APInt(NarrowDefRHS))) ||
1641       !NarrowDefRHS->isNonNegative())
1642     return;
1643 
1644   auto UpdateRangeFromCondition = [&] (Value *Condition,
1645                                        bool TrueDest) {
1646     CmpInst::Predicate Pred;
1647     Value *CmpRHS;
1648     if (!match(Condition, m_ICmp(Pred, m_Specific(NarrowDefLHS),
1649                                  m_Value(CmpRHS))))
1650       return;
1651 
1652     CmpInst::Predicate P =
1653             TrueDest ? Pred : CmpInst::getInversePredicate(Pred);
1654 
1655     auto CmpRHSRange = SE->getSignedRange(SE->getSCEV(CmpRHS));
1656     auto CmpConstrainedLHSRange =
1657             ConstantRange::makeAllowedICmpRegion(P, CmpRHSRange);
1658     auto NarrowDefRange =
1659             CmpConstrainedLHSRange.addWithNoSignedWrap(*NarrowDefRHS);
1660 
1661     updatePostIncRangeInfo(NarrowDef, NarrowUser, NarrowDefRange);
1662   };
1663 
1664   auto UpdateRangeFromGuards = [&](Instruction *Ctx) {
1665     if (!HasGuards)
1666       return;
1667 
1668     for (Instruction &I : make_range(Ctx->getIterator().getReverse(),
1669                                      Ctx->getParent()->rend())) {
1670       Value *C = nullptr;
1671       if (match(&I, m_Intrinsic<Intrinsic::experimental_guard>(m_Value(C))))
1672         UpdateRangeFromCondition(C, /*TrueDest=*/true);
1673     }
1674   };
1675 
1676   UpdateRangeFromGuards(NarrowUser);
1677 
1678   BasicBlock *NarrowUserBB = NarrowUser->getParent();
1679   // If NarrowUserBB is statically unreachable asking dominator queries may
1680   // yield surprising results. (e.g. the block may not have a dom tree node)
1681   if (!DT->isReachableFromEntry(NarrowUserBB))
1682     return;
1683 
1684   for (auto *DTB = (*DT)[NarrowUserBB]->getIDom();
1685        L->contains(DTB->getBlock());
1686        DTB = DTB->getIDom()) {
1687     auto *BB = DTB->getBlock();
1688     auto *TI = BB->getTerminator();
1689     UpdateRangeFromGuards(TI);
1690 
1691     auto *BI = dyn_cast<BranchInst>(TI);
1692     if (!BI || !BI->isConditional())
1693       continue;
1694 
1695     auto *TrueSuccessor = BI->getSuccessor(0);
1696     auto *FalseSuccessor = BI->getSuccessor(1);
1697 
1698     auto DominatesNarrowUser = [this, NarrowUser] (BasicBlockEdge BBE) {
1699       return BBE.isSingleEdge() &&
1700              DT->dominates(BBE, NarrowUser->getParent());
1701     };
1702 
1703     if (DominatesNarrowUser(BasicBlockEdge(BB, TrueSuccessor)))
1704       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/true);
1705 
1706     if (DominatesNarrowUser(BasicBlockEdge(BB, FalseSuccessor)))
1707       UpdateRangeFromCondition(BI->getCondition(), /*TrueDest=*/false);
1708   }
1709 }
1710 
1711 /// Calculates PostIncRangeInfos map for the given IV
1712 void WidenIV::calculatePostIncRanges(PHINode *OrigPhi) {
1713   SmallPtrSet<Instruction *, 16> Visited;
1714   SmallVector<Instruction *, 6> Worklist;
1715   Worklist.push_back(OrigPhi);
1716   Visited.insert(OrigPhi);
1717 
1718   while (!Worklist.empty()) {
1719     Instruction *NarrowDef = Worklist.pop_back_val();
1720 
1721     for (Use &U : NarrowDef->uses()) {
1722       auto *NarrowUser = cast<Instruction>(U.getUser());
1723 
1724       // Don't go looking outside the current loop.
1725       auto *NarrowUserLoop = (*LI)[NarrowUser->getParent()];
1726       if (!NarrowUserLoop || !L->contains(NarrowUserLoop))
1727         continue;
1728 
1729       if (!Visited.insert(NarrowUser).second)
1730         continue;
1731 
1732       Worklist.push_back(NarrowUser);
1733 
1734       calculatePostIncRange(NarrowDef, NarrowUser);
1735     }
1736   }
1737 }
1738 
1739 //===----------------------------------------------------------------------===//
1740 //  Live IV Reduction - Minimize IVs live across the loop.
1741 //===----------------------------------------------------------------------===//
1742 
1743 //===----------------------------------------------------------------------===//
1744 //  Simplification of IV users based on SCEV evaluation.
1745 //===----------------------------------------------------------------------===//
1746 
1747 namespace {
1748 
1749 class IndVarSimplifyVisitor : public IVVisitor {
1750   ScalarEvolution *SE;
1751   const TargetTransformInfo *TTI;
1752   PHINode *IVPhi;
1753 
1754 public:
1755   WideIVInfo WI;
1756 
1757   IndVarSimplifyVisitor(PHINode *IV, ScalarEvolution *SCEV,
1758                         const TargetTransformInfo *TTI,
1759                         const DominatorTree *DTree)
1760     : SE(SCEV), TTI(TTI), IVPhi(IV) {
1761     DT = DTree;
1762     WI.NarrowIV = IVPhi;
1763   }
1764 
1765   // Implement the interface used by simplifyUsersOfIV.
1766   void visitCast(CastInst *Cast) override { visitIVCast(Cast, WI, SE, TTI); }
1767 };
1768 
1769 } // end anonymous namespace
1770 
1771 /// Iteratively perform simplification on a worklist of IV users. Each
1772 /// successive simplification may push more users which may themselves be
1773 /// candidates for simplification.
1774 ///
1775 /// Sign/Zero extend elimination is interleaved with IV simplification.
1776 void IndVarSimplify::simplifyAndExtend(Loop *L,
1777                                        SCEVExpander &Rewriter,
1778                                        LoopInfo *LI) {
1779   SmallVector<WideIVInfo, 8> WideIVs;
1780 
1781   auto *GuardDecl = L->getBlocks()[0]->getModule()->getFunction(
1782           Intrinsic::getName(Intrinsic::experimental_guard));
1783   bool HasGuards = GuardDecl && !GuardDecl->use_empty();
1784 
1785   SmallVector<PHINode*, 8> LoopPhis;
1786   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
1787     LoopPhis.push_back(cast<PHINode>(I));
1788   }
1789   // Each round of simplification iterates through the SimplifyIVUsers worklist
1790   // for all current phis, then determines whether any IVs can be
1791   // widened. Widening adds new phis to LoopPhis, inducing another round of
1792   // simplification on the wide IVs.
1793   while (!LoopPhis.empty()) {
1794     // Evaluate as many IV expressions as possible before widening any IVs. This
1795     // forces SCEV to set no-wrap flags before evaluating sign/zero
1796     // extension. The first time SCEV attempts to normalize sign/zero extension,
1797     // the result becomes final. So for the most predictable results, we delay
1798     // evaluation of sign/zero extend evaluation until needed, and avoid running
1799     // other SCEV based analysis prior to simplifyAndExtend.
1800     do {
1801       PHINode *CurrIV = LoopPhis.pop_back_val();
1802 
1803       // Information about sign/zero extensions of CurrIV.
1804       IndVarSimplifyVisitor Visitor(CurrIV, SE, TTI, DT);
1805 
1806       Changed |=
1807           simplifyUsersOfIV(CurrIV, SE, DT, LI, DeadInsts, Rewriter, &Visitor);
1808 
1809       if (Visitor.WI.WidestNativeType) {
1810         WideIVs.push_back(Visitor.WI);
1811       }
1812     } while(!LoopPhis.empty());
1813 
1814     for (; !WideIVs.empty(); WideIVs.pop_back()) {
1815       WidenIV Widener(WideIVs.back(), LI, SE, DT, DeadInsts, HasGuards);
1816       if (PHINode *WidePhi = Widener.createWideIV(Rewriter)) {
1817         Changed = true;
1818         LoopPhis.push_back(WidePhi);
1819       }
1820     }
1821   }
1822 }
1823 
1824 //===----------------------------------------------------------------------===//
1825 //  linearFunctionTestReplace and its kin. Rewrite the loop exit condition.
1826 //===----------------------------------------------------------------------===//
1827 
1828 /// Return true if this loop's backedge taken count expression can be safely and
1829 /// cheaply expanded into an instruction sequence that can be used by
1830 /// linearFunctionTestReplace.
1831 ///
1832 /// TODO: This fails for pointer-type loop counters with greater than one byte
1833 /// strides, consequently preventing LFTR from running. For the purpose of LFTR
1834 /// we could skip this check in the case that the LFTR loop counter (chosen by
1835 /// FindLoopCounter) is also pointer type. Instead, we could directly convert
1836 /// the loop test to an inequality test by checking the target data's alignment
1837 /// of element types (given that the initial pointer value originates from or is
1838 /// used by ABI constrained operation, as opposed to inttoptr/ptrtoint).
1839 /// However, we don't yet have a strong motivation for converting loop tests
1840 /// into inequality tests.
1841 static bool canExpandBackedgeTakenCount(Loop *L, ScalarEvolution *SE,
1842                                         SCEVExpander &Rewriter) {
1843   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
1844   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
1845       BackedgeTakenCount->isZero())
1846     return false;
1847 
1848   if (!L->getExitingBlock())
1849     return false;
1850 
1851   // Can't rewrite non-branch yet.
1852   if (!isa<BranchInst>(L->getExitingBlock()->getTerminator()))
1853     return false;
1854 
1855   if (Rewriter.isHighCostExpansion(BackedgeTakenCount, L))
1856     return false;
1857 
1858   return true;
1859 }
1860 
1861 /// Return the loop header phi IFF IncV adds a loop invariant value to the phi.
1862 static PHINode *getLoopPhiForCounter(Value *IncV, Loop *L, DominatorTree *DT) {
1863   Instruction *IncI = dyn_cast<Instruction>(IncV);
1864   if (!IncI)
1865     return nullptr;
1866 
1867   switch (IncI->getOpcode()) {
1868   case Instruction::Add:
1869   case Instruction::Sub:
1870     break;
1871   case Instruction::GetElementPtr:
1872     // An IV counter must preserve its type.
1873     if (IncI->getNumOperands() == 2)
1874       break;
1875     LLVM_FALLTHROUGH;
1876   default:
1877     return nullptr;
1878   }
1879 
1880   PHINode *Phi = dyn_cast<PHINode>(IncI->getOperand(0));
1881   if (Phi && Phi->getParent() == L->getHeader()) {
1882     if (isLoopInvariant(IncI->getOperand(1), L, DT))
1883       return Phi;
1884     return nullptr;
1885   }
1886   if (IncI->getOpcode() == Instruction::GetElementPtr)
1887     return nullptr;
1888 
1889   // Allow add/sub to be commuted.
1890   Phi = dyn_cast<PHINode>(IncI->getOperand(1));
1891   if (Phi && Phi->getParent() == L->getHeader()) {
1892     if (isLoopInvariant(IncI->getOperand(0), L, DT))
1893       return Phi;
1894   }
1895   return nullptr;
1896 }
1897 
1898 /// Return the compare guarding the loop latch, or NULL for unrecognized tests.
1899 static ICmpInst *getLoopTest(Loop *L) {
1900   assert(L->getExitingBlock() && "expected loop exit");
1901 
1902   BasicBlock *LatchBlock = L->getLoopLatch();
1903   // Don't bother with LFTR if the loop is not properly simplified.
1904   if (!LatchBlock)
1905     return nullptr;
1906 
1907   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
1908   assert(BI && "expected exit branch");
1909 
1910   return dyn_cast<ICmpInst>(BI->getCondition());
1911 }
1912 
1913 /// linearFunctionTestReplace policy. Return true unless we can show that the
1914 /// current exit test is already sufficiently canonical.
1915 static bool needsLFTR(Loop *L, DominatorTree *DT) {
1916   // Do LFTR to simplify the exit condition to an ICMP.
1917   ICmpInst *Cond = getLoopTest(L);
1918   if (!Cond)
1919     return true;
1920 
1921   // Do LFTR to simplify the exit ICMP to EQ/NE
1922   ICmpInst::Predicate Pred = Cond->getPredicate();
1923   if (Pred != ICmpInst::ICMP_NE && Pred != ICmpInst::ICMP_EQ)
1924     return true;
1925 
1926   // Look for a loop invariant RHS
1927   Value *LHS = Cond->getOperand(0);
1928   Value *RHS = Cond->getOperand(1);
1929   if (!isLoopInvariant(RHS, L, DT)) {
1930     if (!isLoopInvariant(LHS, L, DT))
1931       return true;
1932     std::swap(LHS, RHS);
1933   }
1934   // Look for a simple IV counter LHS
1935   PHINode *Phi = dyn_cast<PHINode>(LHS);
1936   if (!Phi)
1937     Phi = getLoopPhiForCounter(LHS, L, DT);
1938 
1939   if (!Phi)
1940     return true;
1941 
1942   // Do LFTR if PHI node is defined in the loop, but is *not* a counter.
1943   int Idx = Phi->getBasicBlockIndex(L->getLoopLatch());
1944   if (Idx < 0)
1945     return true;
1946 
1947   // Do LFTR if the exit condition's IV is *not* a simple counter.
1948   Value *IncV = Phi->getIncomingValue(Idx);
1949   return Phi != getLoopPhiForCounter(IncV, L, DT);
1950 }
1951 
1952 /// Recursive helper for hasConcreteDef(). Unfortunately, this currently boils
1953 /// down to checking that all operands are constant and listing instructions
1954 /// that may hide undef.
1955 static bool hasConcreteDefImpl(Value *V, SmallPtrSetImpl<Value*> &Visited,
1956                                unsigned Depth) {
1957   if (isa<Constant>(V))
1958     return !isa<UndefValue>(V);
1959 
1960   if (Depth >= 6)
1961     return false;
1962 
1963   // Conservatively handle non-constant non-instructions. For example, Arguments
1964   // may be undef.
1965   Instruction *I = dyn_cast<Instruction>(V);
1966   if (!I)
1967     return false;
1968 
1969   // Load and return values may be undef.
1970   if(I->mayReadFromMemory() || isa<CallInst>(I) || isa<InvokeInst>(I))
1971     return false;
1972 
1973   // Optimistically handle other instructions.
1974   for (Value *Op : I->operands()) {
1975     if (!Visited.insert(Op).second)
1976       continue;
1977     if (!hasConcreteDefImpl(Op, Visited, Depth+1))
1978       return false;
1979   }
1980   return true;
1981 }
1982 
1983 /// Return true if the given value is concrete. We must prove that undef can
1984 /// never reach it.
1985 ///
1986 /// TODO: If we decide that this is a good approach to checking for undef, we
1987 /// may factor it into a common location.
1988 static bool hasConcreteDef(Value *V) {
1989   SmallPtrSet<Value*, 8> Visited;
1990   Visited.insert(V);
1991   return hasConcreteDefImpl(V, Visited, 0);
1992 }
1993 
1994 /// Return true if this IV has any uses other than the (soon to be rewritten)
1995 /// loop exit test.
1996 static bool AlmostDeadIV(PHINode *Phi, BasicBlock *LatchBlock, Value *Cond) {
1997   int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
1998   Value *IncV = Phi->getIncomingValue(LatchIdx);
1999 
2000   for (User *U : Phi->users())
2001     if (U != Cond && U != IncV) return false;
2002 
2003   for (User *U : IncV->users())
2004     if (U != Cond && U != Phi) return false;
2005   return true;
2006 }
2007 
2008 /// Find an affine IV in canonical form.
2009 ///
2010 /// BECount may be an i8* pointer type. The pointer difference is already
2011 /// valid count without scaling the address stride, so it remains a pointer
2012 /// expression as far as SCEV is concerned.
2013 ///
2014 /// Currently only valid for LFTR. See the comments on hasConcreteDef below.
2015 ///
2016 /// FIXME: Accept -1 stride and set IVLimit = IVInit - BECount
2017 ///
2018 /// FIXME: Accept non-unit stride as long as SCEV can reduce BECount * Stride.
2019 /// This is difficult in general for SCEV because of potential overflow. But we
2020 /// could at least handle constant BECounts.
2021 static PHINode *FindLoopCounter(Loop *L, const SCEV *BECount,
2022                                 ScalarEvolution *SE, DominatorTree *DT) {
2023   uint64_t BCWidth = SE->getTypeSizeInBits(BECount->getType());
2024 
2025   Value *Cond =
2026     cast<BranchInst>(L->getExitingBlock()->getTerminator())->getCondition();
2027 
2028   // Loop over all of the PHI nodes, looking for a simple counter.
2029   PHINode *BestPhi = nullptr;
2030   const SCEV *BestInit = nullptr;
2031   BasicBlock *LatchBlock = L->getLoopLatch();
2032   assert(LatchBlock && "needsLFTR should guarantee a loop latch");
2033   const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2034 
2035   for (BasicBlock::iterator I = L->getHeader()->begin(); isa<PHINode>(I); ++I) {
2036     PHINode *Phi = cast<PHINode>(I);
2037     if (!SE->isSCEVable(Phi->getType()))
2038       continue;
2039 
2040     // Avoid comparing an integer IV against a pointer Limit.
2041     if (BECount->getType()->isPointerTy() && !Phi->getType()->isPointerTy())
2042       continue;
2043 
2044     const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(Phi));
2045     if (!AR || AR->getLoop() != L || !AR->isAffine())
2046       continue;
2047 
2048     // AR may be a pointer type, while BECount is an integer type.
2049     // AR may be wider than BECount. With eq/ne tests overflow is immaterial.
2050     // AR may not be a narrower type, or we may never exit.
2051     uint64_t PhiWidth = SE->getTypeSizeInBits(AR->getType());
2052     if (PhiWidth < BCWidth || !DL.isLegalInteger(PhiWidth))
2053       continue;
2054 
2055     const SCEV *Step = dyn_cast<SCEVConstant>(AR->getStepRecurrence(*SE));
2056     if (!Step || !Step->isOne())
2057       continue;
2058 
2059     int LatchIdx = Phi->getBasicBlockIndex(LatchBlock);
2060     Value *IncV = Phi->getIncomingValue(LatchIdx);
2061     if (getLoopPhiForCounter(IncV, L, DT) != Phi)
2062       continue;
2063 
2064     // Avoid reusing a potentially undef value to compute other values that may
2065     // have originally had a concrete definition.
2066     if (!hasConcreteDef(Phi)) {
2067       // We explicitly allow unknown phis as long as they are already used by
2068       // the loop test. In this case we assume that performing LFTR could not
2069       // increase the number of undef users.
2070       if (ICmpInst *Cond = getLoopTest(L)) {
2071         if (Phi != getLoopPhiForCounter(Cond->getOperand(0), L, DT) &&
2072             Phi != getLoopPhiForCounter(Cond->getOperand(1), L, DT)) {
2073           continue;
2074         }
2075       }
2076     }
2077     const SCEV *Init = AR->getStart();
2078 
2079     if (BestPhi && !AlmostDeadIV(BestPhi, LatchBlock, Cond)) {
2080       // Don't force a live loop counter if another IV can be used.
2081       if (AlmostDeadIV(Phi, LatchBlock, Cond))
2082         continue;
2083 
2084       // Prefer to count-from-zero. This is a more "canonical" counter form. It
2085       // also prefers integer to pointer IVs.
2086       if (BestInit->isZero() != Init->isZero()) {
2087         if (BestInit->isZero())
2088           continue;
2089       }
2090       // If two IVs both count from zero or both count from nonzero then the
2091       // narrower is likely a dead phi that has been widened. Use the wider phi
2092       // to allow the other to be eliminated.
2093       else if (PhiWidth <= SE->getTypeSizeInBits(BestPhi->getType()))
2094         continue;
2095     }
2096     BestPhi = Phi;
2097     BestInit = Init;
2098   }
2099   return BestPhi;
2100 }
2101 
2102 /// Help linearFunctionTestReplace by generating a value that holds the RHS of
2103 /// the new loop test.
2104 static Value *genLoopLimit(PHINode *IndVar, const SCEV *IVCount, Loop *L,
2105                            SCEVExpander &Rewriter, ScalarEvolution *SE) {
2106   const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2107   assert(AR && AR->getLoop() == L && AR->isAffine() && "bad loop counter");
2108   const SCEV *IVInit = AR->getStart();
2109 
2110   // IVInit may be a pointer while IVCount is an integer when FindLoopCounter
2111   // finds a valid pointer IV. Sign extend BECount in order to materialize a
2112   // GEP. Avoid running SCEVExpander on a new pointer value, instead reusing
2113   // the existing GEPs whenever possible.
2114   if (IndVar->getType()->isPointerTy() && !IVCount->getType()->isPointerTy()) {
2115     // IVOffset will be the new GEP offset that is interpreted by GEP as a
2116     // signed value. IVCount on the other hand represents the loop trip count,
2117     // which is an unsigned value. FindLoopCounter only allows induction
2118     // variables that have a positive unit stride of one. This means we don't
2119     // have to handle the case of negative offsets (yet) and just need to zero
2120     // extend IVCount.
2121     Type *OfsTy = SE->getEffectiveSCEVType(IVInit->getType());
2122     const SCEV *IVOffset = SE->getTruncateOrZeroExtend(IVCount, OfsTy);
2123 
2124     // Expand the code for the iteration count.
2125     assert(SE->isLoopInvariant(IVOffset, L) &&
2126            "Computed iteration count is not loop invariant!");
2127     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2128     Value *GEPOffset = Rewriter.expandCodeFor(IVOffset, OfsTy, BI);
2129 
2130     Value *GEPBase = IndVar->getIncomingValueForBlock(L->getLoopPreheader());
2131     assert(AR->getStart() == SE->getSCEV(GEPBase) && "bad loop counter");
2132     // We could handle pointer IVs other than i8*, but we need to compensate for
2133     // gep index scaling. See canExpandBackedgeTakenCount comments.
2134     assert(SE->getSizeOfExpr(IntegerType::getInt64Ty(IndVar->getContext()),
2135                              cast<PointerType>(GEPBase->getType())
2136                                  ->getElementType())->isOne() &&
2137            "unit stride pointer IV must be i8*");
2138 
2139     IRBuilder<> Builder(L->getLoopPreheader()->getTerminator());
2140     return Builder.CreateGEP(nullptr, GEPBase, GEPOffset, "lftr.limit");
2141   } else {
2142     // In any other case, convert both IVInit and IVCount to integers before
2143     // comparing. This may result in SCEV expansion of pointers, but in practice
2144     // SCEV will fold the pointer arithmetic away as such:
2145     // BECount = (IVEnd - IVInit - 1) => IVLimit = IVInit (postinc).
2146     //
2147     // Valid Cases: (1) both integers is most common; (2) both may be pointers
2148     // for simple memset-style loops.
2149     //
2150     // IVInit integer and IVCount pointer would only occur if a canonical IV
2151     // were generated on top of case #2, which is not expected.
2152 
2153     const SCEV *IVLimit = nullptr;
2154     // For unit stride, IVCount = Start + BECount with 2's complement overflow.
2155     // For non-zero Start, compute IVCount here.
2156     if (AR->getStart()->isZero())
2157       IVLimit = IVCount;
2158     else {
2159       assert(AR->getStepRecurrence(*SE)->isOne() && "only handles unit stride");
2160       const SCEV *IVInit = AR->getStart();
2161 
2162       // For integer IVs, truncate the IV before computing IVInit + BECount.
2163       if (SE->getTypeSizeInBits(IVInit->getType())
2164           > SE->getTypeSizeInBits(IVCount->getType()))
2165         IVInit = SE->getTruncateExpr(IVInit, IVCount->getType());
2166 
2167       IVLimit = SE->getAddExpr(IVInit, IVCount);
2168     }
2169     // Expand the code for the iteration count.
2170     BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2171     IRBuilder<> Builder(BI);
2172     assert(SE->isLoopInvariant(IVLimit, L) &&
2173            "Computed iteration count is not loop invariant!");
2174     // Ensure that we generate the same type as IndVar, or a smaller integer
2175     // type. In the presence of null pointer values, we have an integer type
2176     // SCEV expression (IVInit) for a pointer type IV value (IndVar).
2177     Type *LimitTy = IVCount->getType()->isPointerTy() ?
2178       IndVar->getType() : IVCount->getType();
2179     return Rewriter.expandCodeFor(IVLimit, LimitTy, BI);
2180   }
2181 }
2182 
2183 /// This method rewrites the exit condition of the loop to be a canonical !=
2184 /// comparison against the incremented loop induction variable.  This pass is
2185 /// able to rewrite the exit tests of any loop where the SCEV analysis can
2186 /// determine a loop-invariant trip count of the loop, which is actually a much
2187 /// broader range than just linear tests.
2188 Value *IndVarSimplify::
2189 linearFunctionTestReplace(Loop *L,
2190                           const SCEV *BackedgeTakenCount,
2191                           PHINode *IndVar,
2192                           SCEVExpander &Rewriter) {
2193   assert(canExpandBackedgeTakenCount(L, SE, Rewriter) && "precondition");
2194 
2195   // Initialize CmpIndVar and IVCount to their preincremented values.
2196   Value *CmpIndVar = IndVar;
2197   const SCEV *IVCount = BackedgeTakenCount;
2198 
2199   assert(L->getLoopLatch() && "Loop no longer in simplified form?");
2200 
2201   // If the exiting block is the same as the backedge block, we prefer to
2202   // compare against the post-incremented value, otherwise we must compare
2203   // against the preincremented value.
2204   if (L->getExitingBlock() == L->getLoopLatch()) {
2205     // Add one to the "backedge-taken" count to get the trip count.
2206     // This addition may overflow, which is valid as long as the comparison is
2207     // truncated to BackedgeTakenCount->getType().
2208     IVCount = SE->getAddExpr(BackedgeTakenCount,
2209                              SE->getOne(BackedgeTakenCount->getType()));
2210     // The BackedgeTaken expression contains the number of times that the
2211     // backedge branches to the loop header.  This is one less than the
2212     // number of times the loop executes, so use the incremented indvar.
2213     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
2214   }
2215 
2216   Value *ExitCnt = genLoopLimit(IndVar, IVCount, L, Rewriter, SE);
2217   assert(ExitCnt->getType()->isPointerTy() ==
2218              IndVar->getType()->isPointerTy() &&
2219          "genLoopLimit missed a cast");
2220 
2221   // Insert a new icmp_ne or icmp_eq instruction before the branch.
2222   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
2223   ICmpInst::Predicate P;
2224   if (L->contains(BI->getSuccessor(0)))
2225     P = ICmpInst::ICMP_NE;
2226   else
2227     P = ICmpInst::ICMP_EQ;
2228 
2229   LLVM_DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
2230                     << "      LHS:" << *CmpIndVar << '\n'
2231                     << "       op:\t" << (P == ICmpInst::ICMP_NE ? "!=" : "==")
2232                     << "\n"
2233                     << "      RHS:\t" << *ExitCnt << "\n"
2234                     << "  IVCount:\t" << *IVCount << "\n");
2235 
2236   IRBuilder<> Builder(BI);
2237 
2238   // The new loop exit condition should reuse the debug location of the
2239   // original loop exit condition.
2240   if (auto *Cond = dyn_cast<Instruction>(BI->getCondition()))
2241     Builder.SetCurrentDebugLocation(Cond->getDebugLoc());
2242 
2243   // LFTR can ignore IV overflow and truncate to the width of
2244   // BECount. This avoids materializing the add(zext(add)) expression.
2245   unsigned CmpIndVarSize = SE->getTypeSizeInBits(CmpIndVar->getType());
2246   unsigned ExitCntSize = SE->getTypeSizeInBits(ExitCnt->getType());
2247   if (CmpIndVarSize > ExitCntSize) {
2248     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(SE->getSCEV(IndVar));
2249     const SCEV *ARStart = AR->getStart();
2250     const SCEV *ARStep = AR->getStepRecurrence(*SE);
2251     // For constant IVCount, avoid truncation.
2252     if (isa<SCEVConstant>(ARStart) && isa<SCEVConstant>(IVCount)) {
2253       const APInt &Start = cast<SCEVConstant>(ARStart)->getAPInt();
2254       APInt Count = cast<SCEVConstant>(IVCount)->getAPInt();
2255       // Note that the post-inc value of BackedgeTakenCount may have overflowed
2256       // above such that IVCount is now zero.
2257       if (IVCount != BackedgeTakenCount && Count == 0) {
2258         Count = APInt::getMaxValue(Count.getBitWidth()).zext(CmpIndVarSize);
2259         ++Count;
2260       }
2261       else
2262         Count = Count.zext(CmpIndVarSize);
2263       APInt NewLimit;
2264       if (cast<SCEVConstant>(ARStep)->getValue()->isNegative())
2265         NewLimit = Start - Count;
2266       else
2267         NewLimit = Start + Count;
2268       ExitCnt = ConstantInt::get(CmpIndVar->getType(), NewLimit);
2269 
2270       LLVM_DEBUG(dbgs() << "  Widen RHS:\t" << *ExitCnt << "\n");
2271     } else {
2272       // We try to extend trip count first. If that doesn't work we truncate IV.
2273       // Zext(trunc(IV)) == IV implies equivalence of the following two:
2274       // Trunc(IV) == ExitCnt and IV == zext(ExitCnt). Similarly for sext. If
2275       // one of the two holds, extend the trip count, otherwise we truncate IV.
2276       bool Extended = false;
2277       const SCEV *IV = SE->getSCEV(CmpIndVar);
2278       const SCEV *ZExtTrunc =
2279            SE->getZeroExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2280                                                      ExitCnt->getType()),
2281                                  CmpIndVar->getType());
2282 
2283       if (ZExtTrunc == IV) {
2284         Extended = true;
2285         ExitCnt = Builder.CreateZExt(ExitCnt, IndVar->getType(),
2286                                      "wide.trip.count");
2287       } else {
2288         const SCEV *SExtTrunc =
2289           SE->getSignExtendExpr(SE->getTruncateExpr(SE->getSCEV(CmpIndVar),
2290                                                     ExitCnt->getType()),
2291                                 CmpIndVar->getType());
2292         if (SExtTrunc == IV) {
2293           Extended = true;
2294           ExitCnt = Builder.CreateSExt(ExitCnt, IndVar->getType(),
2295                                        "wide.trip.count");
2296         }
2297       }
2298 
2299       if (!Extended)
2300         CmpIndVar = Builder.CreateTrunc(CmpIndVar, ExitCnt->getType(),
2301                                         "lftr.wideiv");
2302     }
2303   }
2304   Value *Cond = Builder.CreateICmp(P, CmpIndVar, ExitCnt, "exitcond");
2305   Value *OrigCond = BI->getCondition();
2306   // It's tempting to use replaceAllUsesWith here to fully replace the old
2307   // comparison, but that's not immediately safe, since users of the old
2308   // comparison may not be dominated by the new comparison. Instead, just
2309   // update the branch to use the new comparison; in the common case this
2310   // will make old comparison dead.
2311   BI->setCondition(Cond);
2312   DeadInsts.push_back(OrigCond);
2313 
2314   ++NumLFTR;
2315   Changed = true;
2316   return Cond;
2317 }
2318 
2319 //===----------------------------------------------------------------------===//
2320 //  sinkUnusedInvariants. A late subpass to cleanup loop preheaders.
2321 //===----------------------------------------------------------------------===//
2322 
2323 /// If there's a single exit block, sink any loop-invariant values that
2324 /// were defined in the preheader but not used inside the loop into the
2325 /// exit block to reduce register pressure in the loop.
2326 void IndVarSimplify::sinkUnusedInvariants(Loop *L) {
2327   BasicBlock *ExitBlock = L->getExitBlock();
2328   if (!ExitBlock) return;
2329 
2330   BasicBlock *Preheader = L->getLoopPreheader();
2331   if (!Preheader) return;
2332 
2333   BasicBlock::iterator InsertPt = ExitBlock->getFirstInsertionPt();
2334   BasicBlock::iterator I(Preheader->getTerminator());
2335   while (I != Preheader->begin()) {
2336     --I;
2337     // New instructions were inserted at the end of the preheader.
2338     if (isa<PHINode>(I))
2339       break;
2340 
2341     // Don't move instructions which might have side effects, since the side
2342     // effects need to complete before instructions inside the loop.  Also don't
2343     // move instructions which might read memory, since the loop may modify
2344     // memory. Note that it's okay if the instruction might have undefined
2345     // behavior: LoopSimplify guarantees that the preheader dominates the exit
2346     // block.
2347     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
2348       continue;
2349 
2350     // Skip debug info intrinsics.
2351     if (isa<DbgInfoIntrinsic>(I))
2352       continue;
2353 
2354     // Skip eh pad instructions.
2355     if (I->isEHPad())
2356       continue;
2357 
2358     // Don't sink alloca: we never want to sink static alloca's out of the
2359     // entry block, and correctly sinking dynamic alloca's requires
2360     // checks for stacksave/stackrestore intrinsics.
2361     // FIXME: Refactor this check somehow?
2362     if (isa<AllocaInst>(I))
2363       continue;
2364 
2365     // Determine if there is a use in or before the loop (direct or
2366     // otherwise).
2367     bool UsedInLoop = false;
2368     for (Use &U : I->uses()) {
2369       Instruction *User = cast<Instruction>(U.getUser());
2370       BasicBlock *UseBB = User->getParent();
2371       if (PHINode *P = dyn_cast<PHINode>(User)) {
2372         unsigned i =
2373           PHINode::getIncomingValueNumForOperand(U.getOperandNo());
2374         UseBB = P->getIncomingBlock(i);
2375       }
2376       if (UseBB == Preheader || L->contains(UseBB)) {
2377         UsedInLoop = true;
2378         break;
2379       }
2380     }
2381 
2382     // If there is, the def must remain in the preheader.
2383     if (UsedInLoop)
2384       continue;
2385 
2386     // Otherwise, sink it to the exit block.
2387     Instruction *ToMove = &*I;
2388     bool Done = false;
2389 
2390     if (I != Preheader->begin()) {
2391       // Skip debug info intrinsics.
2392       do {
2393         --I;
2394       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
2395 
2396       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
2397         Done = true;
2398     } else {
2399       Done = true;
2400     }
2401 
2402     ToMove->moveBefore(*ExitBlock, InsertPt);
2403     if (Done) break;
2404     InsertPt = ToMove->getIterator();
2405   }
2406 }
2407 
2408 //===----------------------------------------------------------------------===//
2409 //  IndVarSimplify driver. Manage several subpasses of IV simplification.
2410 //===----------------------------------------------------------------------===//
2411 
2412 bool IndVarSimplify::run(Loop *L) {
2413   // We need (and expect!) the incoming loop to be in LCSSA.
2414   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2415          "LCSSA required to run indvars!");
2416 
2417   // If LoopSimplify form is not available, stay out of trouble. Some notes:
2418   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
2419   //    canonicalization can be a pessimization without LSR to "clean up"
2420   //    afterwards.
2421   //  - We depend on having a preheader; in particular,
2422   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
2423   //    and we're in trouble if we can't find the induction variable even when
2424   //    we've manually inserted one.
2425   //  - LFTR relies on having a single backedge.
2426   if (!L->isLoopSimplifyForm())
2427     return false;
2428 
2429   // If there are any floating-point recurrences, attempt to
2430   // transform them to use integer recurrences.
2431   rewriteNonIntegerIVs(L);
2432 
2433   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
2434 
2435   // Create a rewriter object which we'll use to transform the code with.
2436   SCEVExpander Rewriter(*SE, DL, "indvars");
2437 #ifndef NDEBUG
2438   Rewriter.setDebugType(DEBUG_TYPE);
2439 #endif
2440 
2441   // Eliminate redundant IV users.
2442   //
2443   // Simplification works best when run before other consumers of SCEV. We
2444   // attempt to avoid evaluating SCEVs for sign/zero extend operations until
2445   // other expressions involving loop IVs have been evaluated. This helps SCEV
2446   // set no-wrap flags before normalizing sign/zero extension.
2447   Rewriter.disableCanonicalMode();
2448   simplifyAndExtend(L, Rewriter, LI);
2449 
2450   // Check to see if this loop has a computable loop-invariant execution count.
2451   // If so, this means that we can compute the final value of any expressions
2452   // that are recurrent in the loop, and substitute the exit values from the
2453   // loop into any instructions outside of the loop that use the final values of
2454   // the current expressions.
2455   //
2456   if (ReplaceExitValue != NeverRepl &&
2457       !isa<SCEVCouldNotCompute>(BackedgeTakenCount))
2458     rewriteLoopExitValues(L, Rewriter);
2459 
2460   // Eliminate redundant IV cycles.
2461   NumElimIV += Rewriter.replaceCongruentIVs(L, DT, DeadInsts);
2462 
2463   // If we have a trip count expression, rewrite the loop's exit condition
2464   // using it.  We can currently only handle loops with a single exit.
2465   if (!DisableLFTR && canExpandBackedgeTakenCount(L, SE, Rewriter) &&
2466       needsLFTR(L, DT)) {
2467     PHINode *IndVar = FindLoopCounter(L, BackedgeTakenCount, SE, DT);
2468     if (IndVar) {
2469       // Check preconditions for proper SCEVExpander operation. SCEV does not
2470       // express SCEVExpander's dependencies, such as LoopSimplify. Instead any
2471       // pass that uses the SCEVExpander must do it. This does not work well for
2472       // loop passes because SCEVExpander makes assumptions about all loops,
2473       // while LoopPassManager only forces the current loop to be simplified.
2474       //
2475       // FIXME: SCEV expansion has no way to bail out, so the caller must
2476       // explicitly check any assumptions made by SCEV. Brittle.
2477       const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(BackedgeTakenCount);
2478       if (!AR || AR->getLoop()->getLoopPreheader())
2479         (void)linearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
2480                                         Rewriter);
2481     }
2482   }
2483   // Clear the rewriter cache, because values that are in the rewriter's cache
2484   // can be deleted in the loop below, causing the AssertingVH in the cache to
2485   // trigger.
2486   Rewriter.clear();
2487 
2488   // Now that we're done iterating through lists, clean up any instructions
2489   // which are now dead.
2490   while (!DeadInsts.empty())
2491     if (Instruction *Inst =
2492             dyn_cast_or_null<Instruction>(DeadInsts.pop_back_val()))
2493       RecursivelyDeleteTriviallyDeadInstructions(Inst, TLI);
2494 
2495   // The Rewriter may not be used from this point on.
2496 
2497   // Loop-invariant instructions in the preheader that aren't used in the
2498   // loop may be sunk below the loop to reduce register pressure.
2499   sinkUnusedInvariants(L);
2500 
2501   // rewriteFirstIterationLoopExitValues does not rely on the computation of
2502   // trip count and therefore can further simplify exit values in addition to
2503   // rewriteLoopExitValues.
2504   rewriteFirstIterationLoopExitValues(L);
2505 
2506   // Clean up dead instructions.
2507   Changed |= DeleteDeadPHIs(L->getHeader(), TLI);
2508 
2509   // Check a post-condition.
2510   assert(L->isRecursivelyLCSSAForm(*DT, *LI) &&
2511          "Indvars did not preserve LCSSA!");
2512 
2513   // Verify that LFTR, and any other change have not interfered with SCEV's
2514   // ability to compute trip count.
2515 #ifndef NDEBUG
2516   if (VerifyIndvars && !isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
2517     SE->forgetLoop(L);
2518     const SCEV *NewBECount = SE->getBackedgeTakenCount(L);
2519     if (SE->getTypeSizeInBits(BackedgeTakenCount->getType()) <
2520         SE->getTypeSizeInBits(NewBECount->getType()))
2521       NewBECount = SE->getTruncateOrNoop(NewBECount,
2522                                          BackedgeTakenCount->getType());
2523     else
2524       BackedgeTakenCount = SE->getTruncateOrNoop(BackedgeTakenCount,
2525                                                  NewBECount->getType());
2526     assert(BackedgeTakenCount == NewBECount && "indvars must preserve SCEV");
2527   }
2528 #endif
2529 
2530   return Changed;
2531 }
2532 
2533 PreservedAnalyses IndVarSimplifyPass::run(Loop &L, LoopAnalysisManager &AM,
2534                                           LoopStandardAnalysisResults &AR,
2535                                           LPMUpdater &) {
2536   Function *F = L.getHeader()->getParent();
2537   const DataLayout &DL = F->getParent()->getDataLayout();
2538 
2539   IndVarSimplify IVS(&AR.LI, &AR.SE, &AR.DT, DL, &AR.TLI, &AR.TTI);
2540   if (!IVS.run(&L))
2541     return PreservedAnalyses::all();
2542 
2543   auto PA = getLoopPassPreservedAnalyses();
2544   PA.preserveSet<CFGAnalyses>();
2545   return PA;
2546 }
2547 
2548 namespace {
2549 
2550 struct IndVarSimplifyLegacyPass : public LoopPass {
2551   static char ID; // Pass identification, replacement for typeid
2552 
2553   IndVarSimplifyLegacyPass() : LoopPass(ID) {
2554     initializeIndVarSimplifyLegacyPassPass(*PassRegistry::getPassRegistry());
2555   }
2556 
2557   bool runOnLoop(Loop *L, LPPassManager &LPM) override {
2558     if (skipLoop(L))
2559       return false;
2560 
2561     auto *LI = &getAnalysis<LoopInfoWrapperPass>().getLoopInfo();
2562     auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
2563     auto *DT = &getAnalysis<DominatorTreeWrapperPass>().getDomTree();
2564     auto *TLIP = getAnalysisIfAvailable<TargetLibraryInfoWrapperPass>();
2565     auto *TLI = TLIP ? &TLIP->getTLI() : nullptr;
2566     auto *TTIP = getAnalysisIfAvailable<TargetTransformInfoWrapperPass>();
2567     auto *TTI = TTIP ? &TTIP->getTTI(*L->getHeader()->getParent()) : nullptr;
2568     const DataLayout &DL = L->getHeader()->getModule()->getDataLayout();
2569 
2570     IndVarSimplify IVS(LI, SE, DT, DL, TLI, TTI);
2571     return IVS.run(L);
2572   }
2573 
2574   void getAnalysisUsage(AnalysisUsage &AU) const override {
2575     AU.setPreservesCFG();
2576     getLoopAnalysisUsage(AU);
2577   }
2578 };
2579 
2580 } // end anonymous namespace
2581 
2582 char IndVarSimplifyLegacyPass::ID = 0;
2583 
2584 INITIALIZE_PASS_BEGIN(IndVarSimplifyLegacyPass, "indvars",
2585                       "Induction Variable Simplification", false, false)
2586 INITIALIZE_PASS_DEPENDENCY(LoopPass)
2587 INITIALIZE_PASS_END(IndVarSimplifyLegacyPass, "indvars",
2588                     "Induction Variable Simplification", false, false)
2589 
2590 Pass *llvm::createIndVarSimplifyPass() {
2591   return new IndVarSimplifyLegacyPass();
2592 }
2593