indvars: Added DisableIVRewrite and WidenIVs.
[oota-llvm.git] / lib / Transforms / Scalar / IndVarSimplify.cpp
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 // This transformation makes the following changes to each loop with an
15 // identifiable induction variable:
16 //   1. All loops are transformed to have a SINGLE canonical induction variable
17 //      which starts at zero and steps by one.
18 //   2. The canonical induction variable is guaranteed to be the first PHI node
19 //      in the loop header block.
20 //   3. The canonical induction variable is guaranteed to be in a wide enough
21 //      type so that IV expressions need not be (directly) zero-extended or
22 //      sign-extended.
23 //   4. Any pointer arithmetic recurrences are raised to use array subscripts.
24 //
25 // If the trip count of a loop is computable, this pass also makes the following
26 // changes:
27 //   1. The exit condition for the loop is canonicalized to compare the
28 //      induction value against the exit value.  This turns loops like:
29 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
30 //   2. Any use outside of the loop of an expression derived from the indvar
31 //      is changed to compute the derived value outside of the loop, eliminating
32 //      the dependence on the exit value of the induction variable.  If the only
33 //      purpose of the loop is to compute the exit value of some derived
34 //      expression, this transformation will make the loop dead.
35 //
36 // This transformation should be followed by strength reduction after all of the
37 // desired loop transformations have been performed.
38 //
39 //===----------------------------------------------------------------------===//
40
41 #define DEBUG_TYPE "indvars"
42 #include "llvm/Transforms/Scalar.h"
43 #include "llvm/BasicBlock.h"
44 #include "llvm/Constants.h"
45 #include "llvm/Instructions.h"
46 #include "llvm/IntrinsicInst.h"
47 #include "llvm/LLVMContext.h"
48 #include "llvm/Type.h"
49 #include "llvm/Analysis/Dominators.h"
50 #include "llvm/Analysis/IVUsers.h"
51 #include "llvm/Analysis/ScalarEvolutionExpander.h"
52 #include "llvm/Analysis/LoopInfo.h"
53 #include "llvm/Analysis/LoopPass.h"
54 #include "llvm/Support/CFG.h"
55 #include "llvm/Support/Debug.h"
56 #include "llvm/Support/raw_ostream.h"
57 #include "llvm/Transforms/Utils/Local.h"
58 #include "llvm/Transforms/Utils/BasicBlockUtils.h"
59 #include "llvm/Target/TargetData.h"
60 #include "llvm/ADT/SmallVector.h"
61 #include "llvm/ADT/Statistic.h"
62 #include "llvm/ADT/STLExtras.h"
63 using namespace llvm;
64
65 STATISTIC(NumRemoved , "Number of aux indvars removed");
66 STATISTIC(NumWidened , "Number of indvars widened");
67 STATISTIC(NumInserted, "Number of canonical indvars added");
68 STATISTIC(NumReplaced, "Number of exit values replaced");
69 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
70
71 // DisableIVRewrite mode currently affects IVUsers, so is defined in libAnalysis
72 // and referenced here.
73 namespace llvm {
74   extern bool DisableIVRewrite;
75 }
76
77 namespace {
78   class IndVarSimplify : public LoopPass {
79     IVUsers         *IU;
80     LoopInfo        *LI;
81     ScalarEvolution *SE;
82     DominatorTree   *DT;
83     TargetData      *TD;
84     SmallVector<WeakVH, 16> DeadInsts;
85     bool Changed;
86   public:
87
88     static char ID; // Pass identification, replacement for typeid
89     IndVarSimplify() : LoopPass(ID), IU(0), LI(0), SE(0), DT(0), TD(0) {
90       initializeIndVarSimplifyPass(*PassRegistry::getPassRegistry());
91     }
92
93     virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
94
95     virtual void getAnalysisUsage(AnalysisUsage &AU) const {
96       AU.addRequired<DominatorTree>();
97       AU.addRequired<LoopInfo>();
98       AU.addRequired<ScalarEvolution>();
99       AU.addRequiredID(LoopSimplifyID);
100       AU.addRequiredID(LCSSAID);
101       AU.addRequired<IVUsers>();
102       AU.addPreserved<ScalarEvolution>();
103       AU.addPreservedID(LoopSimplifyID);
104       AU.addPreservedID(LCSSAID);
105       AU.addPreserved<IVUsers>();
106       AU.setPreservesCFG();
107     }
108
109   private:
110     bool isValidRewrite(Value *FromVal, Value *ToVal);
111
112     void EliminateIVComparisons();
113     void EliminateIVRemainders();
114     void RewriteNonIntegerIVs(Loop *L);
115     const Type *WidenIVs(Loop *L, SCEVExpander &Rewriter);
116
117     bool canExpandBackedgeTakenCount(Loop *L,
118                                      const SCEV *BackedgeTakenCount);
119
120     ICmpInst *LinearFunctionTestReplace(Loop *L, const SCEV *BackedgeTakenCount,
121                                         PHINode *IndVar,
122                                         SCEVExpander &Rewriter);
123
124     void RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter);
125
126     void RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter);
127
128     void SinkUnusedInvariants(Loop *L);
129
130     void HandleFloatingPointIV(Loop *L, PHINode *PH);
131   };
132 }
133
134 char IndVarSimplify::ID = 0;
135 INITIALIZE_PASS_BEGIN(IndVarSimplify, "indvars",
136                 "Induction Variable Simplification", false, false)
137 INITIALIZE_PASS_DEPENDENCY(DominatorTree)
138 INITIALIZE_PASS_DEPENDENCY(LoopInfo)
139 INITIALIZE_PASS_DEPENDENCY(ScalarEvolution)
140 INITIALIZE_PASS_DEPENDENCY(LoopSimplify)
141 INITIALIZE_PASS_DEPENDENCY(LCSSA)
142 INITIALIZE_PASS_DEPENDENCY(IVUsers)
143 INITIALIZE_PASS_END(IndVarSimplify, "indvars",
144                 "Induction Variable Simplification", false, false)
145
146 Pass *llvm::createIndVarSimplifyPass() {
147   return new IndVarSimplify();
148 }
149
150 /// isValidRewrite - Return true if the SCEV expansion generated by the
151 /// rewriter can replace the original value. SCEV guarantees that it
152 /// produces the same value, but the way it is produced may be illegal IR.
153 /// Ideally, this function will only be called for verification.
154 bool IndVarSimplify::isValidRewrite(Value *FromVal, Value *ToVal) {
155   // If an SCEV expression subsumed multiple pointers, its expansion could
156   // reassociate the GEP changing the base pointer. This is illegal because the
157   // final address produced by a GEP chain must be inbounds relative to its
158   // underlying object. Otherwise basic alias analysis, among other things,
159   // could fail in a dangerous way. Ultimately, SCEV will be improved to avoid
160   // producing an expression involving multiple pointers. Until then, we must
161   // bail out here.
162   //
163   // Retrieve the pointer operand of the GEP. Don't use GetUnderlyingObject
164   // because it understands lcssa phis while SCEV does not.
165   Value *FromPtr = FromVal;
166   Value *ToPtr = ToVal;
167   if (GEPOperator *GEP = dyn_cast<GEPOperator>(FromVal)) {
168     FromPtr = GEP->getPointerOperand();
169   }
170   if (GEPOperator *GEP = dyn_cast<GEPOperator>(ToVal)) {
171     ToPtr = GEP->getPointerOperand();
172   }
173   if (FromPtr != FromVal || ToPtr != ToVal) {
174     // Quickly check the common case
175     if (FromPtr == ToPtr)
176       return true;
177
178     // SCEV may have rewritten an expression that produces the GEP's pointer
179     // operand. That's ok as long as the pointer operand has the same base
180     // pointer. Unlike GetUnderlyingObject(), getPointerBase() will find the
181     // base of a recurrence. This handles the case in which SCEV expansion
182     // converts a pointer type recurrence into a nonrecurrent pointer base
183     // indexed by an integer recurrence.
184     const SCEV *FromBase = SE->getPointerBase(SE->getSCEV(FromPtr));
185     const SCEV *ToBase = SE->getPointerBase(SE->getSCEV(ToPtr));
186     if (FromBase == ToBase)
187       return true;
188
189     DEBUG(dbgs() << "INDVARS: GEP rewrite bail out "
190           << *FromBase << " != " << *ToBase << "\n");
191
192     return false;
193   }
194   return true;
195 }
196
197 /// canExpandBackedgeTakenCount - Return true if this loop's backedge taken
198 /// count expression can be safely and cheaply expanded into an instruction
199 /// sequence that can be used by LinearFunctionTestReplace.
200 bool IndVarSimplify::
201 canExpandBackedgeTakenCount(Loop *L,
202                             const SCEV *BackedgeTakenCount) {
203   if (isa<SCEVCouldNotCompute>(BackedgeTakenCount) ||
204       BackedgeTakenCount->isZero())
205     return false;
206
207   if (!L->getExitingBlock())
208     return false;
209
210   // Can't rewrite non-branch yet.
211   BranchInst *BI = dyn_cast<BranchInst>(L->getExitingBlock()->getTerminator());
212   if (!BI)
213     return false;
214
215   // Special case: If the backedge-taken count is a UDiv, it's very likely a
216   // UDiv that ScalarEvolution produced in order to compute a precise
217   // expression, rather than a UDiv from the user's code. If we can't find a
218   // UDiv in the code with some simple searching, assume the former and forego
219   // rewriting the loop.
220   if (isa<SCEVUDivExpr>(BackedgeTakenCount)) {
221     ICmpInst *OrigCond = dyn_cast<ICmpInst>(BI->getCondition());
222     if (!OrigCond) return false;
223     const SCEV *R = SE->getSCEV(OrigCond->getOperand(1));
224     R = SE->getMinusSCEV(R, SE->getConstant(R->getType(), 1));
225     if (R != BackedgeTakenCount) {
226       const SCEV *L = SE->getSCEV(OrigCond->getOperand(0));
227       L = SE->getMinusSCEV(L, SE->getConstant(L->getType(), 1));
228       if (L != BackedgeTakenCount)
229         return false;
230     }
231   }
232   return true;
233 }
234
235 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
236 /// loop to be a canonical != comparison against the incremented loop induction
237 /// variable.  This pass is able to rewrite the exit tests of any loop where the
238 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
239 /// is actually a much broader range than just linear tests.
240 ICmpInst *IndVarSimplify::
241 LinearFunctionTestReplace(Loop *L,
242                           const SCEV *BackedgeTakenCount,
243                           PHINode *IndVar,
244                           SCEVExpander &Rewriter) {
245   assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) && "precondition");
246   BranchInst *BI = cast<BranchInst>(L->getExitingBlock()->getTerminator());
247
248   // If the exiting block is not the same as the backedge block, we must compare
249   // against the preincremented value, otherwise we prefer to compare against
250   // the post-incremented value.
251   Value *CmpIndVar;
252   const SCEV *RHS = BackedgeTakenCount;
253   if (L->getExitingBlock() == L->getLoopLatch()) {
254     // Add one to the "backedge-taken" count to get the trip count.
255     // If this addition may overflow, we have to be more pessimistic and
256     // cast the induction variable before doing the add.
257     const SCEV *Zero = SE->getConstant(BackedgeTakenCount->getType(), 0);
258     const SCEV *N =
259       SE->getAddExpr(BackedgeTakenCount,
260                      SE->getConstant(BackedgeTakenCount->getType(), 1));
261     if ((isa<SCEVConstant>(N) && !N->isZero()) ||
262         SE->isLoopEntryGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
263       // No overflow. Cast the sum.
264       RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
265     } else {
266       // Potential overflow. Cast before doing the add.
267       RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
268                                         IndVar->getType());
269       RHS = SE->getAddExpr(RHS,
270                            SE->getConstant(IndVar->getType(), 1));
271     }
272
273     // The BackedgeTaken expression contains the number of times that the
274     // backedge branches to the loop header.  This is one less than the
275     // number of times the loop executes, so use the incremented indvar.
276     CmpIndVar = IndVar->getIncomingValueForBlock(L->getExitingBlock());
277   } else {
278     // We have to use the preincremented value...
279     RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
280                                       IndVar->getType());
281     CmpIndVar = IndVar;
282   }
283
284   // Expand the code for the iteration count.
285   assert(SE->isLoopInvariant(RHS, L) &&
286          "Computed iteration count is not loop invariant!");
287   Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(), BI);
288
289   // Insert a new icmp_ne or icmp_eq instruction before the branch.
290   ICmpInst::Predicate Opcode;
291   if (L->contains(BI->getSuccessor(0)))
292     Opcode = ICmpInst::ICMP_NE;
293   else
294     Opcode = ICmpInst::ICMP_EQ;
295
296   DEBUG(dbgs() << "INDVARS: Rewriting loop exit condition to:\n"
297                << "      LHS:" << *CmpIndVar << '\n'
298                << "       op:\t"
299                << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
300                << "      RHS:\t" << *RHS << "\n");
301
302   ICmpInst *Cond = new ICmpInst(BI, Opcode, CmpIndVar, ExitCnt, "exitcond");
303
304   Value *OrigCond = BI->getCondition();
305   // It's tempting to use replaceAllUsesWith here to fully replace the old
306   // comparison, but that's not immediately safe, since users of the old
307   // comparison may not be dominated by the new comparison. Instead, just
308   // update the branch to use the new comparison; in the common case this
309   // will make old comparison dead.
310   BI->setCondition(Cond);
311   DeadInsts.push_back(OrigCond);
312
313   ++NumLFTR;
314   Changed = true;
315   return Cond;
316 }
317
318 /// RewriteLoopExitValues - Check to see if this loop has a computable
319 /// loop-invariant execution count.  If so, this means that we can compute the
320 /// final value of any expressions that are recurrent in the loop, and
321 /// substitute the exit values from the loop into any instructions outside of
322 /// the loop that use the final values of the current expressions.
323 ///
324 /// This is mostly redundant with the regular IndVarSimplify activities that
325 /// happen later, except that it's more powerful in some cases, because it's
326 /// able to brute-force evaluate arbitrary instructions as long as they have
327 /// constant operands at the beginning of the loop.
328 void IndVarSimplify::RewriteLoopExitValues(Loop *L, SCEVExpander &Rewriter) {
329   // Verify the input to the pass in already in LCSSA form.
330   assert(L->isLCSSAForm(*DT));
331
332   SmallVector<BasicBlock*, 8> ExitBlocks;
333   L->getUniqueExitBlocks(ExitBlocks);
334
335   // Find all values that are computed inside the loop, but used outside of it.
336   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
337   // the exit blocks of the loop to find them.
338   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
339     BasicBlock *ExitBB = ExitBlocks[i];
340
341     // If there are no PHI nodes in this exit block, then no values defined
342     // inside the loop are used on this path, skip it.
343     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
344     if (!PN) continue;
345
346     unsigned NumPreds = PN->getNumIncomingValues();
347
348     // Iterate over all of the PHI nodes.
349     BasicBlock::iterator BBI = ExitBB->begin();
350     while ((PN = dyn_cast<PHINode>(BBI++))) {
351       if (PN->use_empty())
352         continue; // dead use, don't replace it
353
354       // SCEV only supports integer expressions for now.
355       if (!PN->getType()->isIntegerTy() && !PN->getType()->isPointerTy())
356         continue;
357
358       // It's necessary to tell ScalarEvolution about this explicitly so that
359       // it can walk the def-use list and forget all SCEVs, as it may not be
360       // watching the PHI itself. Once the new exit value is in place, there
361       // may not be a def-use connection between the loop and every instruction
362       // which got a SCEVAddRecExpr for that loop.
363       SE->forgetValue(PN);
364
365       // Iterate over all of the values in all the PHI nodes.
366       for (unsigned i = 0; i != NumPreds; ++i) {
367         // If the value being merged in is not integer or is not defined
368         // in the loop, skip it.
369         Value *InVal = PN->getIncomingValue(i);
370         if (!isa<Instruction>(InVal))
371           continue;
372
373         // If this pred is for a subloop, not L itself, skip it.
374         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
375           continue; // The Block is in a subloop, skip it.
376
377         // Check that InVal is defined in the loop.
378         Instruction *Inst = cast<Instruction>(InVal);
379         if (!L->contains(Inst))
380           continue;
381
382         // Okay, this instruction has a user outside of the current loop
383         // and varies predictably *inside* the loop.  Evaluate the value it
384         // contains when the loop exits, if possible.
385         const SCEV *ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
386         if (!SE->isLoopInvariant(ExitValue, L))
387           continue;
388
389         Value *ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), Inst);
390
391         DEBUG(dbgs() << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal << '\n'
392                      << "  LoopVal = " << *Inst << "\n");
393
394         if (!isValidRewrite(Inst, ExitVal)) {
395           DeadInsts.push_back(ExitVal);
396           continue;
397         }
398         Changed = true;
399         ++NumReplaced;
400
401         PN->setIncomingValue(i, ExitVal);
402
403         // If this instruction is dead now, delete it.
404         RecursivelyDeleteTriviallyDeadInstructions(Inst);
405
406         if (NumPreds == 1) {
407           // Completely replace a single-pred PHI. This is safe, because the
408           // NewVal won't be variant in the loop, so we don't need an LCSSA phi
409           // node anymore.
410           PN->replaceAllUsesWith(ExitVal);
411           RecursivelyDeleteTriviallyDeadInstructions(PN);
412         }
413       }
414       if (NumPreds != 1) {
415         // Clone the PHI and delete the original one. This lets IVUsers and
416         // any other maps purge the original user from their records.
417         PHINode *NewPN = cast<PHINode>(PN->clone());
418         NewPN->takeName(PN);
419         NewPN->insertBefore(PN);
420         PN->replaceAllUsesWith(NewPN);
421         PN->eraseFromParent();
422       }
423     }
424   }
425
426   // The insertion point instruction may have been deleted; clear it out
427   // so that the rewriter doesn't trip over it later.
428   Rewriter.clearInsertPoint();
429 }
430
431 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
432   // First step.  Check to see if there are any floating-point recurrences.
433   // If there are, change them into integer recurrences, permitting analysis by
434   // the SCEV routines.
435   //
436   BasicBlock *Header = L->getHeader();
437
438   SmallVector<WeakVH, 8> PHIs;
439   for (BasicBlock::iterator I = Header->begin();
440        PHINode *PN = dyn_cast<PHINode>(I); ++I)
441     PHIs.push_back(PN);
442
443   for (unsigned i = 0, e = PHIs.size(); i != e; ++i)
444     if (PHINode *PN = dyn_cast_or_null<PHINode>(&*PHIs[i]))
445       HandleFloatingPointIV(L, PN);
446
447   // If the loop previously had floating-point IV, ScalarEvolution
448   // may not have been able to compute a trip count. Now that we've done some
449   // re-writing, the trip count may be computable.
450   if (Changed)
451     SE->forgetLoop(L);
452 }
453
454 void IndVarSimplify::EliminateIVComparisons() {
455   // Look for ICmp users.
456   for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
457     IVStrideUse &UI = *I;
458     ICmpInst *ICmp = dyn_cast<ICmpInst>(UI.getUser());
459     if (!ICmp) continue;
460
461     bool Swapped = UI.getOperandValToReplace() == ICmp->getOperand(1);
462     ICmpInst::Predicate Pred = ICmp->getPredicate();
463     if (Swapped) Pred = ICmpInst::getSwappedPredicate(Pred);
464
465     // Get the SCEVs for the ICmp operands.
466     const SCEV *S = IU->getReplacementExpr(UI);
467     const SCEV *X = SE->getSCEV(ICmp->getOperand(!Swapped));
468
469     // Simplify unnecessary loops away.
470     const Loop *ICmpLoop = LI->getLoopFor(ICmp->getParent());
471     S = SE->getSCEVAtScope(S, ICmpLoop);
472     X = SE->getSCEVAtScope(X, ICmpLoop);
473
474     // If the condition is always true or always false, replace it with
475     // a constant value.
476     if (SE->isKnownPredicate(Pred, S, X))
477       ICmp->replaceAllUsesWith(ConstantInt::getTrue(ICmp->getContext()));
478     else if (SE->isKnownPredicate(ICmpInst::getInversePredicate(Pred), S, X))
479       ICmp->replaceAllUsesWith(ConstantInt::getFalse(ICmp->getContext()));
480     else
481       continue;
482
483     DEBUG(dbgs() << "INDVARS: Eliminated comparison: " << *ICmp << '\n');
484     DeadInsts.push_back(ICmp);
485   }
486 }
487
488 void IndVarSimplify::EliminateIVRemainders() {
489   // Look for SRem and URem users.
490   for (IVUsers::iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
491     IVStrideUse &UI = *I;
492     BinaryOperator *Rem = dyn_cast<BinaryOperator>(UI.getUser());
493     if (!Rem) continue;
494
495     bool isSigned = Rem->getOpcode() == Instruction::SRem;
496     if (!isSigned && Rem->getOpcode() != Instruction::URem)
497       continue;
498
499     // We're only interested in the case where we know something about
500     // the numerator.
501     if (UI.getOperandValToReplace() != Rem->getOperand(0))
502       continue;
503
504     // Get the SCEVs for the ICmp operands.
505     const SCEV *S = SE->getSCEV(Rem->getOperand(0));
506     const SCEV *X = SE->getSCEV(Rem->getOperand(1));
507
508     // Simplify unnecessary loops away.
509     const Loop *ICmpLoop = LI->getLoopFor(Rem->getParent());
510     S = SE->getSCEVAtScope(S, ICmpLoop);
511     X = SE->getSCEVAtScope(X, ICmpLoop);
512
513     // i % n  -->  i  if i is in [0,n).
514     if ((!isSigned || SE->isKnownNonNegative(S)) &&
515         SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
516                              S, X))
517       Rem->replaceAllUsesWith(Rem->getOperand(0));
518     else {
519       // (i+1) % n  -->  (i+1)==n?0:(i+1)  if i is in [0,n).
520       const SCEV *LessOne =
521         SE->getMinusSCEV(S, SE->getConstant(S->getType(), 1));
522       if ((!isSigned || SE->isKnownNonNegative(LessOne)) &&
523           SE->isKnownPredicate(isSigned ? ICmpInst::ICMP_SLT : ICmpInst::ICMP_ULT,
524                                LessOne, X)) {
525         ICmpInst *ICmp = new ICmpInst(Rem, ICmpInst::ICMP_EQ,
526                                       Rem->getOperand(0), Rem->getOperand(1),
527                                       "tmp");
528         SelectInst *Sel =
529           SelectInst::Create(ICmp,
530                              ConstantInt::get(Rem->getType(), 0),
531                              Rem->getOperand(0), "tmp", Rem);
532         Rem->replaceAllUsesWith(Sel);
533       } else
534         continue;
535     }
536
537     // Inform IVUsers about the new users.
538     if (Instruction *I = dyn_cast<Instruction>(Rem->getOperand(0)))
539       IU->AddUsersIfInteresting(I);
540
541     DEBUG(dbgs() << "INDVARS: Simplified rem: " << *Rem << '\n');
542     DeadInsts.push_back(Rem);
543   }
544 }
545
546 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
547   // If LoopSimplify form is not available, stay out of trouble. Some notes:
548   //  - LSR currently only supports LoopSimplify-form loops. Indvars'
549   //    canonicalization can be a pessimization without LSR to "clean up"
550   //    afterwards.
551   //  - We depend on having a preheader; in particular,
552   //    Loop::getCanonicalInductionVariable only supports loops with preheaders,
553   //    and we're in trouble if we can't find the induction variable even when
554   //    we've manually inserted one.
555   if (!L->isLoopSimplifyForm())
556     return false;
557
558   IU = &getAnalysis<IVUsers>();
559   LI = &getAnalysis<LoopInfo>();
560   SE = &getAnalysis<ScalarEvolution>();
561   DT = &getAnalysis<DominatorTree>();
562   TD = getAnalysisIfAvailable<TargetData>();
563
564   DeadInsts.clear();
565   Changed = false;
566
567   // If there are any floating-point recurrences, attempt to
568   // transform them to use integer recurrences.
569   RewriteNonIntegerIVs(L);
570
571   const SCEV *BackedgeTakenCount = SE->getBackedgeTakenCount(L);
572
573   // Create a rewriter object which we'll use to transform the code with.
574   SCEVExpander Rewriter(*SE);
575   if (DisableIVRewrite)
576     Rewriter.disableCanonicalMode();
577
578   const Type *LargestType = 0;
579   if (DisableIVRewrite) {
580     LargestType = WidenIVs(L, Rewriter);
581   }
582
583   // Check to see if this loop has a computable loop-invariant execution count.
584   // If so, this means that we can compute the final value of any expressions
585   // that are recurrent in the loop, and substitute the exit values from the
586   // loop into any instructions outside of the loop that use the final values of
587   // the current expressions.
588   //
589   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
590     RewriteLoopExitValues(L, Rewriter);
591
592   // Simplify ICmp IV users.
593   EliminateIVComparisons();
594
595   // Simplify SRem and URem IV users.
596   EliminateIVRemainders();
597
598   // Compute the type of the largest recurrence expression, and decide whether
599   // a canonical induction variable should be inserted.
600   bool NeedCannIV = false;
601   bool ExpandBECount = canExpandBackedgeTakenCount(L, BackedgeTakenCount);
602   if (ExpandBECount) {
603     // If we have a known trip count and a single exit block, we'll be
604     // rewriting the loop exit test condition below, which requires a
605     // canonical induction variable.
606     NeedCannIV = true;
607     const Type *Ty = BackedgeTakenCount->getType();
608     if (!LargestType ||
609         SE->getTypeSizeInBits(Ty) >
610         SE->getTypeSizeInBits(LargestType))
611       LargestType = SE->getEffectiveSCEVType(Ty);
612   }
613   for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
614     NeedCannIV = true;
615     const Type *Ty =
616       SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
617     if (!LargestType ||
618         SE->getTypeSizeInBits(Ty) >
619         SE->getTypeSizeInBits(LargestType))
620       LargestType = SE->getEffectiveSCEVType(Ty);
621   }
622   if (!DisableIVRewrite) {
623     for (IVUsers::const_iterator I = IU->begin(), E = IU->end(); I != E; ++I) {
624       NeedCannIV = true;
625       const Type *Ty =
626         SE->getEffectiveSCEVType(I->getOperandValToReplace()->getType());
627       if (!LargestType ||
628           SE->getTypeSizeInBits(Ty) >
629           SE->getTypeSizeInBits(LargestType))
630         LargestType = Ty;
631     }
632   }
633
634   // Now that we know the largest of the induction variable expressions
635   // in this loop, insert a canonical induction variable of the largest size.
636   PHINode *IndVar = 0;
637   if (NeedCannIV) {
638     // Check to see if the loop already has any canonical-looking induction
639     // variables. If any are present and wider than the planned canonical
640     // induction variable, temporarily remove them, so that the Rewriter
641     // doesn't attempt to reuse them.
642     SmallVector<PHINode *, 2> OldCannIVs;
643     while (PHINode *OldCannIV = L->getCanonicalInductionVariable()) {
644       if (SE->getTypeSizeInBits(OldCannIV->getType()) >
645           SE->getTypeSizeInBits(LargestType))
646         OldCannIV->removeFromParent();
647       else
648         break;
649       OldCannIVs.push_back(OldCannIV);
650     }
651
652     IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L, LargestType);
653
654     ++NumInserted;
655     Changed = true;
656     DEBUG(dbgs() << "INDVARS: New CanIV: " << *IndVar << '\n');
657
658     // Now that the official induction variable is established, reinsert
659     // any old canonical-looking variables after it so that the IR remains
660     // consistent. They will be deleted as part of the dead-PHI deletion at
661     // the end of the pass.
662     while (!OldCannIVs.empty()) {
663       PHINode *OldCannIV = OldCannIVs.pop_back_val();
664       OldCannIV->insertBefore(L->getHeader()->getFirstNonPHI());
665     }
666   }
667
668   // If we have a trip count expression, rewrite the loop's exit condition
669   // using it.  We can currently only handle loops with a single exit.
670   ICmpInst *NewICmp = 0;
671   if (ExpandBECount) {
672     assert(canExpandBackedgeTakenCount(L, BackedgeTakenCount) &&
673            "canonical IV disrupted BackedgeTaken expansion");
674     assert(NeedCannIV &&
675            "LinearFunctionTestReplace requires a canonical induction variable");
676     NewICmp = LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
677                                         Rewriter);
678   }
679   // Rewrite IV-derived expressions.
680   if (!DisableIVRewrite)
681     RewriteIVExpressions(L, Rewriter);
682
683   // Clear the rewriter cache, because values that are in the rewriter's cache
684   // can be deleted in the loop below, causing the AssertingVH in the cache to
685   // trigger.
686   Rewriter.clear();
687
688   // Now that we're done iterating through lists, clean up any instructions
689   // which are now dead.
690   while (!DeadInsts.empty())
691     if (Instruction *Inst =
692           dyn_cast_or_null<Instruction>(&*DeadInsts.pop_back_val()))
693       RecursivelyDeleteTriviallyDeadInstructions(Inst);
694
695   // The Rewriter may not be used from this point on.
696
697   // Loop-invariant instructions in the preheader that aren't used in the
698   // loop may be sunk below the loop to reduce register pressure.
699   SinkUnusedInvariants(L);
700
701   // For completeness, inform IVUsers of the IV use in the newly-created
702   // loop exit test instruction.
703   if (NewICmp)
704     IU->AddUsersIfInteresting(cast<Instruction>(NewICmp->getOperand(0)));
705
706   // Clean up dead instructions.
707   Changed |= DeleteDeadPHIs(L->getHeader());
708   // Check a post-condition.
709   assert(L->isLCSSAForm(*DT) && "Indvars did not leave the loop in lcssa form!");
710   return Changed;
711 }
712
713 // FIXME: It is an extremely bad idea to indvar substitute anything more
714 // complex than affine induction variables.  Doing so will put expensive
715 // polynomial evaluations inside of the loop, and the str reduction pass
716 // currently can only reduce affine polynomials.  For now just disable
717 // indvar subst on anything more complex than an affine addrec, unless
718 // it can be expanded to a trivial value.
719 static bool isSafe(const SCEV *S, const Loop *L, ScalarEvolution *SE) {
720   // Loop-invariant values are safe.
721   if (SE->isLoopInvariant(S, L)) return true;
722
723   // Affine addrecs are safe. Non-affine are not, because LSR doesn't know how
724   // to transform them into efficient code.
725   if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(S))
726     return AR->isAffine();
727
728   // An add is safe it all its operands are safe.
729   if (const SCEVCommutativeExpr *Commutative = dyn_cast<SCEVCommutativeExpr>(S)) {
730     for (SCEVCommutativeExpr::op_iterator I = Commutative->op_begin(),
731          E = Commutative->op_end(); I != E; ++I)
732       if (!isSafe(*I, L, SE)) return false;
733     return true;
734   }
735
736   // A cast is safe if its operand is.
737   if (const SCEVCastExpr *C = dyn_cast<SCEVCastExpr>(S))
738     return isSafe(C->getOperand(), L, SE);
739
740   // A udiv is safe if its operands are.
741   if (const SCEVUDivExpr *UD = dyn_cast<SCEVUDivExpr>(S))
742     return isSafe(UD->getLHS(), L, SE) &&
743            isSafe(UD->getRHS(), L, SE);
744
745   // SCEVUnknown is always safe.
746   if (isa<SCEVUnknown>(S))
747     return true;
748
749   // Nothing else is safe.
750   return false;
751 }
752
753 /// Widen the type of any induction variables that are sign/zero extended and
754 /// remove the [sz]ext uses.
755 ///
756 /// FIXME: This may currently create extra IVs which could increase regpressure
757 /// (without LSR to cleanup).
758 ///
759 /// FIXME: may factor this with RewriteIVExpressions once it stabilizes.
760 const Type *IndVarSimplify::WidenIVs(Loop *L, SCEVExpander &Rewriter) {
761   const Type *LargestType = 0;
762   for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
763     Instruction *ExtInst = UI->getUser();
764     if (!isa<SExtInst>(ExtInst) && !isa<ZExtInst>(ExtInst))
765       continue;
766     const SCEV *AR = SE->getSCEV(ExtInst);
767     // Only widen this IV is SCEV tells us it's safe.
768     if (!isa<SCEVAddRecExpr>(AR) && !isa<SCEVAddExpr>(AR))
769       continue;
770
771     if (!L->contains(UI->getUser())) {
772       const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
773       if (SE->isLoopInvariant(ExitVal, L))
774         AR = ExitVal;
775     }
776
777     // Only expand affine recurences.
778     if (!isSafe(AR, L, SE))
779       continue;
780
781     const Type *Ty =
782       SE->getEffectiveSCEVType(ExtInst->getType());
783
784     // Only remove [sz]ext if the wide IV is still a native type.
785     //
786     // FIXME: We may be able to remove the copy of this logic in
787     // IVUsers::AddUsersIfInteresting.
788     uint64_t Width = SE->getTypeSizeInBits(Ty);
789     if (Width > 64 || (TD && !TD->isLegalInteger(Width)))
790       continue;
791
792     // Now expand it into actual Instructions and patch it into place.
793     //
794     // FIXME: avoid creating a new IV.
795     Value *NewVal = Rewriter.expandCodeFor(AR, Ty, ExtInst);
796
797     DEBUG(dbgs() << "INDVARS: Widened IV '" << *AR << "' " << *ExtInst << '\n'
798                  << "   into = " << *NewVal << "\n");
799
800     if (!isValidRewrite(ExtInst, NewVal)) {
801       DeadInsts.push_back(NewVal);
802       continue;
803     }
804
805     ++NumWidened;
806     Changed = true;
807
808     if (!LargestType ||
809         SE->getTypeSizeInBits(Ty) >
810         SE->getTypeSizeInBits(LargestType))
811       LargestType = Ty;
812
813     SE->forgetValue(ExtInst);
814
815     // Patch the new value into place.
816     if (ExtInst->hasName())
817       NewVal->takeName(ExtInst);
818     ExtInst->replaceAllUsesWith(NewVal);
819
820     // The old value may be dead now.
821     DeadInsts.push_back(ExtInst);
822
823     // UI is a linked list iterator, so AddUsersIfInteresting effectively pushes
824     // nodes on the worklist.
825     IU->AddUsersIfInteresting(ExtInst);
826   }
827   return LargestType;
828 }
829
830 void IndVarSimplify::RewriteIVExpressions(Loop *L, SCEVExpander &Rewriter) {
831   // Rewrite all induction variable expressions in terms of the canonical
832   // induction variable.
833   //
834   // If there were induction variables of other sizes or offsets, manually
835   // add the offsets to the primary induction variable and cast, avoiding
836   // the need for the code evaluation methods to insert induction variables
837   // of different sizes.
838   for (IVUsers::iterator UI = IU->begin(), E = IU->end(); UI != E; ++UI) {
839     Value *Op = UI->getOperandValToReplace();
840     const Type *UseTy = Op->getType();
841     Instruction *User = UI->getUser();
842
843     // Compute the final addrec to expand into code.
844     const SCEV *AR = IU->getReplacementExpr(*UI);
845
846     // Evaluate the expression out of the loop, if possible.
847     if (!L->contains(UI->getUser())) {
848       const SCEV *ExitVal = SE->getSCEVAtScope(AR, L->getParentLoop());
849       if (SE->isLoopInvariant(ExitVal, L))
850         AR = ExitVal;
851     }
852
853     // FIXME: It is an extremely bad idea to indvar substitute anything more
854     // complex than affine induction variables.  Doing so will put expensive
855     // polynomial evaluations inside of the loop, and the str reduction pass
856     // currently can only reduce affine polynomials.  For now just disable
857     // indvar subst on anything more complex than an affine addrec, unless
858     // it can be expanded to a trivial value.
859     if (!isSafe(AR, L, SE))
860       continue;
861
862     // Determine the insertion point for this user. By default, insert
863     // immediately before the user. The SCEVExpander class will automatically
864     // hoist loop invariants out of the loop. For PHI nodes, there may be
865     // multiple uses, so compute the nearest common dominator for the
866     // incoming blocks.
867     Instruction *InsertPt = User;
868     if (PHINode *PHI = dyn_cast<PHINode>(InsertPt))
869       for (unsigned i = 0, e = PHI->getNumIncomingValues(); i != e; ++i)
870         if (PHI->getIncomingValue(i) == Op) {
871           if (InsertPt == User)
872             InsertPt = PHI->getIncomingBlock(i)->getTerminator();
873           else
874             InsertPt =
875               DT->findNearestCommonDominator(InsertPt->getParent(),
876                                              PHI->getIncomingBlock(i))
877                     ->getTerminator();
878         }
879
880     // Now expand it into actual Instructions and patch it into place.
881     Value *NewVal = Rewriter.expandCodeFor(AR, UseTy, InsertPt);
882
883     DEBUG(dbgs() << "INDVARS: Rewrote IV '" << *AR << "' " << *Op << '\n'
884                  << "   into = " << *NewVal << "\n");
885
886     if (!isValidRewrite(Op, NewVal)) {
887       DeadInsts.push_back(NewVal);
888       continue;
889     }
890     // Inform ScalarEvolution that this value is changing. The change doesn't
891     // affect its value, but it does potentially affect which use lists the
892     // value will be on after the replacement, which affects ScalarEvolution's
893     // ability to walk use lists and drop dangling pointers when a value is
894     // deleted.
895     SE->forgetValue(User);
896
897     // Patch the new value into place.
898     if (Op->hasName())
899       NewVal->takeName(Op);
900     User->replaceUsesOfWith(Op, NewVal);
901     UI->setOperandValToReplace(NewVal);
902
903     ++NumRemoved;
904     Changed = true;
905
906     // The old value may be dead now.
907     DeadInsts.push_back(Op);
908   }
909 }
910
911 /// If there's a single exit block, sink any loop-invariant values that
912 /// were defined in the preheader but not used inside the loop into the
913 /// exit block to reduce register pressure in the loop.
914 void IndVarSimplify::SinkUnusedInvariants(Loop *L) {
915   BasicBlock *ExitBlock = L->getExitBlock();
916   if (!ExitBlock) return;
917
918   BasicBlock *Preheader = L->getLoopPreheader();
919   if (!Preheader) return;
920
921   Instruction *InsertPt = ExitBlock->getFirstNonPHI();
922   BasicBlock::iterator I = Preheader->getTerminator();
923   while (I != Preheader->begin()) {
924     --I;
925     // New instructions were inserted at the end of the preheader.
926     if (isa<PHINode>(I))
927       break;
928
929     // Don't move instructions which might have side effects, since the side
930     // effects need to complete before instructions inside the loop.  Also don't
931     // move instructions which might read memory, since the loop may modify
932     // memory. Note that it's okay if the instruction might have undefined
933     // behavior: LoopSimplify guarantees that the preheader dominates the exit
934     // block.
935     if (I->mayHaveSideEffects() || I->mayReadFromMemory())
936       continue;
937
938     // Skip debug info intrinsics.
939     if (isa<DbgInfoIntrinsic>(I))
940       continue;
941
942     // Don't sink static AllocaInsts out of the entry block, which would
943     // turn them into dynamic allocas!
944     if (AllocaInst *AI = dyn_cast<AllocaInst>(I))
945       if (AI->isStaticAlloca())
946         continue;
947
948     // Determine if there is a use in or before the loop (direct or
949     // otherwise).
950     bool UsedInLoop = false;
951     for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
952          UI != UE; ++UI) {
953       User *U = *UI;
954       BasicBlock *UseBB = cast<Instruction>(U)->getParent();
955       if (PHINode *P = dyn_cast<PHINode>(U)) {
956         unsigned i =
957           PHINode::getIncomingValueNumForOperand(UI.getOperandNo());
958         UseBB = P->getIncomingBlock(i);
959       }
960       if (UseBB == Preheader || L->contains(UseBB)) {
961         UsedInLoop = true;
962         break;
963       }
964     }
965
966     // If there is, the def must remain in the preheader.
967     if (UsedInLoop)
968       continue;
969
970     // Otherwise, sink it to the exit block.
971     Instruction *ToMove = I;
972     bool Done = false;
973
974     if (I != Preheader->begin()) {
975       // Skip debug info intrinsics.
976       do {
977         --I;
978       } while (isa<DbgInfoIntrinsic>(I) && I != Preheader->begin());
979
980       if (isa<DbgInfoIntrinsic>(I) && I == Preheader->begin())
981         Done = true;
982     } else {
983       Done = true;
984     }
985
986     ToMove->moveBefore(InsertPt);
987     if (Done) break;
988     InsertPt = ToMove;
989   }
990 }
991
992 /// ConvertToSInt - Convert APF to an integer, if possible.
993 static bool ConvertToSInt(const APFloat &APF, int64_t &IntVal) {
994   bool isExact = false;
995   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
996     return false;
997   // See if we can convert this to an int64_t
998   uint64_t UIntVal;
999   if (APF.convertToInteger(&UIntVal, 64, true, APFloat::rmTowardZero,
1000                            &isExact) != APFloat::opOK || !isExact)
1001     return false;
1002   IntVal = UIntVal;
1003   return true;
1004 }
1005
1006 /// HandleFloatingPointIV - If the loop has floating induction variable
1007 /// then insert corresponding integer induction variable if possible.
1008 /// For example,
1009 /// for(double i = 0; i < 10000; ++i)
1010 ///   bar(i)
1011 /// is converted into
1012 /// for(int i = 0; i < 10000; ++i)
1013 ///   bar((double)i);
1014 ///
1015 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PN) {
1016   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
1017   unsigned BackEdge     = IncomingEdge^1;
1018
1019   // Check incoming value.
1020   ConstantFP *InitValueVal =
1021     dyn_cast<ConstantFP>(PN->getIncomingValue(IncomingEdge));
1022
1023   int64_t InitValue;
1024   if (!InitValueVal || !ConvertToSInt(InitValueVal->getValueAPF(), InitValue))
1025     return;
1026
1027   // Check IV increment. Reject this PN if increment operation is not
1028   // an add or increment value can not be represented by an integer.
1029   BinaryOperator *Incr =
1030     dyn_cast<BinaryOperator>(PN->getIncomingValue(BackEdge));
1031   if (Incr == 0 || Incr->getOpcode() != Instruction::FAdd) return;
1032
1033   // If this is not an add of the PHI with a constantfp, or if the constant fp
1034   // is not an integer, bail out.
1035   ConstantFP *IncValueVal = dyn_cast<ConstantFP>(Incr->getOperand(1));
1036   int64_t IncValue;
1037   if (IncValueVal == 0 || Incr->getOperand(0) != PN ||
1038       !ConvertToSInt(IncValueVal->getValueAPF(), IncValue))
1039     return;
1040
1041   // Check Incr uses. One user is PN and the other user is an exit condition
1042   // used by the conditional terminator.
1043   Value::use_iterator IncrUse = Incr->use_begin();
1044   Instruction *U1 = cast<Instruction>(*IncrUse++);
1045   if (IncrUse == Incr->use_end()) return;
1046   Instruction *U2 = cast<Instruction>(*IncrUse++);
1047   if (IncrUse != Incr->use_end()) return;
1048
1049   // Find exit condition, which is an fcmp.  If it doesn't exist, or if it isn't
1050   // only used by a branch, we can't transform it.
1051   FCmpInst *Compare = dyn_cast<FCmpInst>(U1);
1052   if (!Compare)
1053     Compare = dyn_cast<FCmpInst>(U2);
1054   if (Compare == 0 || !Compare->hasOneUse() ||
1055       !isa<BranchInst>(Compare->use_back()))
1056     return;
1057
1058   BranchInst *TheBr = cast<BranchInst>(Compare->use_back());
1059
1060   // We need to verify that the branch actually controls the iteration count
1061   // of the loop.  If not, the new IV can overflow and no one will notice.
1062   // The branch block must be in the loop and one of the successors must be out
1063   // of the loop.
1064   assert(TheBr->isConditional() && "Can't use fcmp if not conditional");
1065   if (!L->contains(TheBr->getParent()) ||
1066       (L->contains(TheBr->getSuccessor(0)) &&
1067        L->contains(TheBr->getSuccessor(1))))
1068     return;
1069
1070
1071   // If it isn't a comparison with an integer-as-fp (the exit value), we can't
1072   // transform it.
1073   ConstantFP *ExitValueVal = dyn_cast<ConstantFP>(Compare->getOperand(1));
1074   int64_t ExitValue;
1075   if (ExitValueVal == 0 ||
1076       !ConvertToSInt(ExitValueVal->getValueAPF(), ExitValue))
1077     return;
1078
1079   // Find new predicate for integer comparison.
1080   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
1081   switch (Compare->getPredicate()) {
1082   default: return;  // Unknown comparison.
1083   case CmpInst::FCMP_OEQ:
1084   case CmpInst::FCMP_UEQ: NewPred = CmpInst::ICMP_EQ; break;
1085   case CmpInst::FCMP_ONE:
1086   case CmpInst::FCMP_UNE: NewPred = CmpInst::ICMP_NE; break;
1087   case CmpInst::FCMP_OGT:
1088   case CmpInst::FCMP_UGT: NewPred = CmpInst::ICMP_SGT; break;
1089   case CmpInst::FCMP_OGE:
1090   case CmpInst::FCMP_UGE: NewPred = CmpInst::ICMP_SGE; break;
1091   case CmpInst::FCMP_OLT:
1092   case CmpInst::FCMP_ULT: NewPred = CmpInst::ICMP_SLT; break;
1093   case CmpInst::FCMP_OLE:
1094   case CmpInst::FCMP_ULE: NewPred = CmpInst::ICMP_SLE; break;
1095   }
1096
1097   // We convert the floating point induction variable to a signed i32 value if
1098   // we can.  This is only safe if the comparison will not overflow in a way
1099   // that won't be trapped by the integer equivalent operations.  Check for this
1100   // now.
1101   // TODO: We could use i64 if it is native and the range requires it.
1102
1103   // The start/stride/exit values must all fit in signed i32.
1104   if (!isInt<32>(InitValue) || !isInt<32>(IncValue) || !isInt<32>(ExitValue))
1105     return;
1106
1107   // If not actually striding (add x, 0.0), avoid touching the code.
1108   if (IncValue == 0)
1109     return;
1110
1111   // Positive and negative strides have different safety conditions.
1112   if (IncValue > 0) {
1113     // If we have a positive stride, we require the init to be less than the
1114     // exit value and an equality or less than comparison.
1115     if (InitValue >= ExitValue ||
1116         NewPred == CmpInst::ICMP_SGT || NewPred == CmpInst::ICMP_SGE)
1117       return;
1118
1119     uint32_t Range = uint32_t(ExitValue-InitValue);
1120     if (NewPred == CmpInst::ICMP_SLE) {
1121       // Normalize SLE -> SLT, check for infinite loop.
1122       if (++Range == 0) return;  // Range overflows.
1123     }
1124
1125     unsigned Leftover = Range % uint32_t(IncValue);
1126
1127     // If this is an equality comparison, we require that the strided value
1128     // exactly land on the exit value, otherwise the IV condition will wrap
1129     // around and do things the fp IV wouldn't.
1130     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1131         Leftover != 0)
1132       return;
1133
1134     // If the stride would wrap around the i32 before exiting, we can't
1135     // transform the IV.
1136     if (Leftover != 0 && int32_t(ExitValue+IncValue) < ExitValue)
1137       return;
1138
1139   } else {
1140     // If we have a negative stride, we require the init to be greater than the
1141     // exit value and an equality or greater than comparison.
1142     if (InitValue >= ExitValue ||
1143         NewPred == CmpInst::ICMP_SLT || NewPred == CmpInst::ICMP_SLE)
1144       return;
1145
1146     uint32_t Range = uint32_t(InitValue-ExitValue);
1147     if (NewPred == CmpInst::ICMP_SGE) {
1148       // Normalize SGE -> SGT, check for infinite loop.
1149       if (++Range == 0) return;  // Range overflows.
1150     }
1151
1152     unsigned Leftover = Range % uint32_t(-IncValue);
1153
1154     // If this is an equality comparison, we require that the strided value
1155     // exactly land on the exit value, otherwise the IV condition will wrap
1156     // around and do things the fp IV wouldn't.
1157     if ((NewPred == CmpInst::ICMP_EQ || NewPred == CmpInst::ICMP_NE) &&
1158         Leftover != 0)
1159       return;
1160
1161     // If the stride would wrap around the i32 before exiting, we can't
1162     // transform the IV.
1163     if (Leftover != 0 && int32_t(ExitValue+IncValue) > ExitValue)
1164       return;
1165   }
1166
1167   const IntegerType *Int32Ty = Type::getInt32Ty(PN->getContext());
1168
1169   // Insert new integer induction variable.
1170   PHINode *NewPHI = PHINode::Create(Int32Ty, 2, PN->getName()+".int", PN);
1171   NewPHI->addIncoming(ConstantInt::get(Int32Ty, InitValue),
1172                       PN->getIncomingBlock(IncomingEdge));
1173
1174   Value *NewAdd =
1175     BinaryOperator::CreateAdd(NewPHI, ConstantInt::get(Int32Ty, IncValue),
1176                               Incr->getName()+".int", Incr);
1177   NewPHI->addIncoming(NewAdd, PN->getIncomingBlock(BackEdge));
1178
1179   ICmpInst *NewCompare = new ICmpInst(TheBr, NewPred, NewAdd,
1180                                       ConstantInt::get(Int32Ty, ExitValue),
1181                                       Compare->getName());
1182
1183   // In the following deletions, PN may become dead and may be deleted.
1184   // Use a WeakVH to observe whether this happens.
1185   WeakVH WeakPH = PN;
1186
1187   // Delete the old floating point exit comparison.  The branch starts using the
1188   // new comparison.
1189   NewCompare->takeName(Compare);
1190   Compare->replaceAllUsesWith(NewCompare);
1191   RecursivelyDeleteTriviallyDeadInstructions(Compare);
1192
1193   // Delete the old floating point increment.
1194   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1195   RecursivelyDeleteTriviallyDeadInstructions(Incr);
1196
1197   // If the FP induction variable still has uses, this is because something else
1198   // in the loop uses its value.  In order to canonicalize the induction
1199   // variable, we chose to eliminate the IV and rewrite it in terms of an
1200   // int->fp cast.
1201   //
1202   // We give preference to sitofp over uitofp because it is faster on most
1203   // platforms.
1204   if (WeakPH) {
1205     Value *Conv = new SIToFPInst(NewPHI, PN->getType(), "indvar.conv",
1206                                  PN->getParent()->getFirstNonPHI());
1207     PN->replaceAllUsesWith(Conv);
1208     RecursivelyDeleteTriviallyDeadInstructions(PN);
1209   }
1210
1211   // Add a new IVUsers entry for the newly-created integer PHI.
1212   IU->AddUsersIfInteresting(NewPHI);
1213 }