Make sure to use signed arithmetic in APInt to fix a regression.
[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. Any pointer arithmetic recurrences are raised to use array subscripts.
21 //
22 // If the trip count of a loop is computable, this pass also makes the following
23 // changes:
24 //   1. The exit condition for the loop is canonicalized to compare the
25 //      induction value against the exit value.  This turns loops like:
26 //        'for (i = 7; i*i < 1000; ++i)' into 'for (i = 0; i != 25; ++i)'
27 //   2. Any use outside of the loop of an expression derived from the indvar
28 //      is changed to compute the derived value outside of the loop, eliminating
29 //      the dependence on the exit value of the induction variable.  If the only
30 //      purpose of the loop is to compute the exit value of some derived
31 //      expression, this transformation will make the loop dead.
32 //
33 // This transformation should be followed by strength reduction after all of the
34 // desired loop transformations have been performed.  Additionally, on targets
35 // where it is profitable, the loop could be transformed to count down to zero
36 // (the "do loop" optimization).
37 //
38 //===----------------------------------------------------------------------===//
39
40 #define DEBUG_TYPE "indvars"
41 #include "llvm/Transforms/Scalar.h"
42 #include "llvm/BasicBlock.h"
43 #include "llvm/Constants.h"
44 #include "llvm/Instructions.h"
45 #include "llvm/Type.h"
46 #include "llvm/Analysis/ScalarEvolutionExpander.h"
47 #include "llvm/Analysis/LoopInfo.h"
48 #include "llvm/Analysis/LoopPass.h"
49 #include "llvm/Support/CFG.h"
50 #include "llvm/Support/Compiler.h"
51 #include "llvm/Support/Debug.h"
52 #include "llvm/Support/GetElementPtrTypeIterator.h"
53 #include "llvm/Transforms/Utils/Local.h"
54 #include "llvm/Support/CommandLine.h"
55 #include "llvm/ADT/SmallVector.h"
56 #include "llvm/ADT/SetVector.h"
57 #include "llvm/ADT/SmallPtrSet.h"
58 #include "llvm/ADT/Statistic.h"
59 using namespace llvm;
60
61 STATISTIC(NumRemoved , "Number of aux indvars removed");
62 STATISTIC(NumInserted, "Number of canonical indvars added");
63 STATISTIC(NumReplaced, "Number of exit values replaced");
64 STATISTIC(NumLFTR    , "Number of loop exit tests replaced");
65
66 namespace {
67   class VISIBILITY_HIDDEN IndVarSimplify : public LoopPass {
68     LoopInfo        *LI;
69     ScalarEvolution *SE;
70     bool Changed;
71   public:
72
73    static char ID; // Pass identification, replacement for typeid
74    IndVarSimplify() : LoopPass(&ID) {}
75
76    virtual bool runOnLoop(Loop *L, LPPassManager &LPM);
77
78    virtual void getAnalysisUsage(AnalysisUsage &AU) const {
79      AU.addRequired<ScalarEvolution>();
80      AU.addRequiredID(LCSSAID);
81      AU.addRequiredID(LoopSimplifyID);
82      AU.addRequired<LoopInfo>();
83      AU.addPreserved<ScalarEvolution>();
84      AU.addPreservedID(LoopSimplifyID);
85      AU.addPreservedID(LCSSAID);
86      AU.setPreservesCFG();
87    }
88
89   private:
90
91     void RewriteNonIntegerIVs(Loop *L);
92
93     void LinearFunctionTestReplace(Loop *L, SCEVHandle BackedgeTakenCount,
94                                    Value *IndVar,
95                                    BasicBlock *ExitingBlock,
96                                    BranchInst *BI,
97                                    SCEVExpander &Rewriter);
98     void RewriteLoopExitValues(Loop *L, const SCEV *BackedgeTakenCount);
99
100     void DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts);
101
102     void HandleFloatingPointIV(Loop *L, PHINode *PH,
103                                SmallPtrSet<Instruction*, 16> &DeadInsts);
104   };
105 }
106
107 char IndVarSimplify::ID = 0;
108 static RegisterPass<IndVarSimplify>
109 X("indvars", "Canonicalize Induction Variables");
110
111 Pass *llvm::createIndVarSimplifyPass() {
112   return new IndVarSimplify();
113 }
114
115 /// DeleteTriviallyDeadInstructions - If any of the instructions is the
116 /// specified set are trivially dead, delete them and see if this makes any of
117 /// their operands subsequently dead.
118 void IndVarSimplify::
119 DeleteTriviallyDeadInstructions(SmallPtrSet<Instruction*, 16> &Insts) {
120   while (!Insts.empty()) {
121     Instruction *I = *Insts.begin();
122     Insts.erase(I);
123     if (isInstructionTriviallyDead(I)) {
124       for (unsigned i = 0, e = I->getNumOperands(); i != e; ++i)
125         if (Instruction *U = dyn_cast<Instruction>(I->getOperand(i)))
126           Insts.insert(U);
127       DOUT << "INDVARS: Deleting: " << *I;
128       I->eraseFromParent();
129       Changed = true;
130     }
131   }
132 }
133
134 /// LinearFunctionTestReplace - This method rewrites the exit condition of the
135 /// loop to be a canonical != comparison against the incremented loop induction
136 /// variable.  This pass is able to rewrite the exit tests of any loop where the
137 /// SCEV analysis can determine a loop-invariant trip count of the loop, which
138 /// is actually a much broader range than just linear tests.
139 void IndVarSimplify::LinearFunctionTestReplace(Loop *L,
140                                    SCEVHandle BackedgeTakenCount,
141                                    Value *IndVar,
142                                    BasicBlock *ExitingBlock,
143                                    BranchInst *BI,
144                                    SCEVExpander &Rewriter) {
145   // If the exiting block is not the same as the backedge block, we must compare
146   // against the preincremented value, otherwise we prefer to compare against
147   // the post-incremented value.
148   Value *CmpIndVar;
149   SCEVHandle RHS = BackedgeTakenCount;
150   if (ExitingBlock == L->getLoopLatch()) {
151     // Add one to the "backedge-taken" count to get the trip count.
152     // If this addition may overflow, we have to be more pessimistic and
153     // cast the induction variable before doing the add.
154     SCEVHandle Zero = SE->getIntegerSCEV(0, BackedgeTakenCount->getType());
155     SCEVHandle N =
156       SE->getAddExpr(BackedgeTakenCount,
157                      SE->getIntegerSCEV(1, BackedgeTakenCount->getType()));
158     if ((isa<SCEVConstant>(N) && !N->isZero()) ||
159         SE->isLoopGuardedByCond(L, ICmpInst::ICMP_NE, N, Zero)) {
160       // No overflow. Cast the sum.
161       RHS = SE->getTruncateOrZeroExtend(N, IndVar->getType());
162     } else {
163       // Potential overflow. Cast before doing the add.
164       RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
165                                         IndVar->getType());
166       RHS = SE->getAddExpr(RHS,
167                            SE->getIntegerSCEV(1, IndVar->getType()));
168     }
169
170     // The BackedgeTaken expression contains the number of times that the
171     // backedge branches to the loop header.  This is one less than the
172     // number of times the loop executes, so use the incremented indvar.
173     CmpIndVar = L->getCanonicalInductionVariableIncrement();
174   } else {
175     // We have to use the preincremented value...
176     RHS = SE->getTruncateOrZeroExtend(BackedgeTakenCount,
177                                       IndVar->getType());
178     CmpIndVar = IndVar;
179   }
180
181   // Expand the code for the iteration count into the preheader of the loop.
182   BasicBlock *Preheader = L->getLoopPreheader();
183   Value *ExitCnt = Rewriter.expandCodeFor(RHS, IndVar->getType(),
184                                           Preheader->getTerminator());
185
186   // Insert a new icmp_ne or icmp_eq instruction before the branch.
187   ICmpInst::Predicate Opcode;
188   if (L->contains(BI->getSuccessor(0)))
189     Opcode = ICmpInst::ICMP_NE;
190   else
191     Opcode = ICmpInst::ICMP_EQ;
192
193   DOUT << "INDVARS: Rewriting loop exit condition to:\n"
194        << "      LHS:" << *CmpIndVar // includes a newline
195        << "       op:\t"
196        << (Opcode == ICmpInst::ICMP_NE ? "!=" : "==") << "\n"
197        << "      RHS:\t" << *RHS << "\n";
198
199   Value *Cond = new ICmpInst(Opcode, CmpIndVar, ExitCnt, "exitcond", BI);
200   BI->setCondition(Cond);
201   ++NumLFTR;
202   Changed = true;
203 }
204
205 /// RewriteLoopExitValues - Check to see if this loop has a computable
206 /// loop-invariant execution count.  If so, this means that we can compute the
207 /// final value of any expressions that are recurrent in the loop, and
208 /// substitute the exit values from the loop into any instructions outside of
209 /// the loop that use the final values of the current expressions.
210 void IndVarSimplify::RewriteLoopExitValues(Loop *L,
211                                            const SCEV *BackedgeTakenCount) {
212   BasicBlock *Preheader = L->getLoopPreheader();
213
214   // Scan all of the instructions in the loop, looking at those that have
215   // extra-loop users and which are recurrences.
216   SCEVExpander Rewriter(*SE, *LI);
217
218   // We insert the code into the preheader of the loop if the loop contains
219   // multiple exit blocks, or in the exit block if there is exactly one.
220   BasicBlock *BlockToInsertInto;
221   SmallVector<BasicBlock*, 8> ExitBlocks;
222   L->getUniqueExitBlocks(ExitBlocks);
223   if (ExitBlocks.size() == 1)
224     BlockToInsertInto = ExitBlocks[0];
225   else
226     BlockToInsertInto = Preheader;
227   BasicBlock::iterator InsertPt = BlockToInsertInto->getFirstNonPHI();
228
229   bool HasConstantItCount = isa<SCEVConstant>(BackedgeTakenCount);
230
231   SmallPtrSet<Instruction*, 16> InstructionsToDelete;
232   std::map<Instruction*, Value*> ExitValues;
233
234   // Find all values that are computed inside the loop, but used outside of it.
235   // Because of LCSSA, these values will only occur in LCSSA PHI Nodes.  Scan
236   // the exit blocks of the loop to find them.
237   for (unsigned i = 0, e = ExitBlocks.size(); i != e; ++i) {
238     BasicBlock *ExitBB = ExitBlocks[i];
239
240     // If there are no PHI nodes in this exit block, then no values defined
241     // inside the loop are used on this path, skip it.
242     PHINode *PN = dyn_cast<PHINode>(ExitBB->begin());
243     if (!PN) continue;
244
245     unsigned NumPreds = PN->getNumIncomingValues();
246
247     // Iterate over all of the PHI nodes.
248     BasicBlock::iterator BBI = ExitBB->begin();
249     while ((PN = dyn_cast<PHINode>(BBI++))) {
250
251       // Iterate over all of the values in all the PHI nodes.
252       for (unsigned i = 0; i != NumPreds; ++i) {
253         // If the value being merged in is not integer or is not defined
254         // in the loop, skip it.
255         Value *InVal = PN->getIncomingValue(i);
256         if (!isa<Instruction>(InVal) ||
257             // SCEV only supports integer expressions for now.
258             (!isa<IntegerType>(InVal->getType()) &&
259              !isa<PointerType>(InVal->getType())))
260           continue;
261
262         // If this pred is for a subloop, not L itself, skip it.
263         if (LI->getLoopFor(PN->getIncomingBlock(i)) != L)
264           continue; // The Block is in a subloop, skip it.
265
266         // Check that InVal is defined in the loop.
267         Instruction *Inst = cast<Instruction>(InVal);
268         if (!L->contains(Inst->getParent()))
269           continue;
270
271         // We require that this value either have a computable evolution or that
272         // the loop have a constant iteration count.  In the case where the loop
273         // has a constant iteration count, we can sometimes force evaluation of
274         // the exit value through brute force.
275         SCEVHandle SH = SE->getSCEV(Inst);
276         if (!SH->hasComputableLoopEvolution(L) && !HasConstantItCount)
277           continue;          // Cannot get exit evolution for the loop value.
278
279         // Okay, this instruction has a user outside of the current loop
280         // and varies predictably *inside* the loop.  Evaluate the value it
281         // contains when the loop exits, if possible.
282         SCEVHandle ExitValue = SE->getSCEVAtScope(Inst, L->getParentLoop());
283         if (isa<SCEVCouldNotCompute>(ExitValue) ||
284             !ExitValue->isLoopInvariant(L))
285           continue;
286
287         Changed = true;
288         ++NumReplaced;
289
290         // See if we already computed the exit value for the instruction, if so,
291         // just reuse it.
292         Value *&ExitVal = ExitValues[Inst];
293         if (!ExitVal)
294           ExitVal = Rewriter.expandCodeFor(ExitValue, PN->getType(), InsertPt);
295
296         DOUT << "INDVARS: RLEV: AfterLoopVal = " << *ExitVal
297              << "  LoopVal = " << *Inst << "\n";
298
299         PN->setIncomingValue(i, ExitVal);
300
301         // If this instruction is dead now, schedule it to be removed.
302         if (Inst->use_empty())
303           InstructionsToDelete.insert(Inst);
304
305         // See if this is a single-entry LCSSA PHI node.  If so, we can (and
306         // have to) remove
307         // the PHI entirely.  This is safe, because the NewVal won't be variant
308         // in the loop, so we don't need an LCSSA phi node anymore.
309         if (NumPreds == 1) {
310           PN->replaceAllUsesWith(ExitVal);
311           PN->eraseFromParent();
312           break;
313         }
314       }
315     }
316   }
317
318   DeleteTriviallyDeadInstructions(InstructionsToDelete);
319 }
320
321 void IndVarSimplify::RewriteNonIntegerIVs(Loop *L) {
322   // First step.  Check to see if there are any floating-point recurrences.
323   // If there are, change them into integer recurrences, permitting analysis by
324   // the SCEV routines.
325   //
326   BasicBlock *Header    = L->getHeader();
327
328   SmallPtrSet<Instruction*, 16> DeadInsts;
329   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
330     PHINode *PN = cast<PHINode>(I);
331     HandleFloatingPointIV(L, PN, DeadInsts);
332   }
333
334   // If the loop previously had floating-point IV, ScalarEvolution
335   // may not have been able to compute a trip count. Now that we've done some
336   // re-writing, the trip count may be computable.
337   if (Changed)
338     SE->forgetLoopBackedgeTakenCount(L);
339
340   if (!DeadInsts.empty())
341     DeleteTriviallyDeadInstructions(DeadInsts);
342 }
343
344 /// getEffectiveIndvarType - Determine the widest type that the
345 /// induction-variable PHINode Phi is cast to.
346 ///
347 static const Type *getEffectiveIndvarType(const PHINode *Phi,
348                                           const ScalarEvolution *SE) {
349   const Type *Ty = Phi->getType();
350
351   for (Value::use_const_iterator UI = Phi->use_begin(), UE = Phi->use_end();
352        UI != UE; ++UI) {
353     const Type *CandidateType = NULL;
354     if (const ZExtInst *ZI = dyn_cast<ZExtInst>(UI))
355       CandidateType = ZI->getDestTy();
356     else if (const SExtInst *SI = dyn_cast<SExtInst>(UI))
357       CandidateType = SI->getDestTy();
358     else if (const IntToPtrInst *IP = dyn_cast<IntToPtrInst>(UI))
359       CandidateType = IP->getDestTy();
360     else if (const PtrToIntInst *PI = dyn_cast<PtrToIntInst>(UI))
361       CandidateType = PI->getDestTy();
362     if (CandidateType &&
363         SE->isSCEVable(CandidateType) &&
364         SE->getTypeSizeInBits(CandidateType) > SE->getTypeSizeInBits(Ty))
365       Ty = CandidateType;
366   }
367
368   return Ty;
369 }
370
371 /// TestOrigIVForWrap - Analyze the original induction variable that
372 /// controls the loop's iteration to determine whether it would ever
373 /// undergo signed or unsigned overflow.
374 ///
375 /// In addition to setting the NoSignedWrap and NoUnsignedWrap
376 /// variables to true when appropriate (they are not set to false here),
377 /// return the PHI for this induction variable.  Also record the initial
378 /// and final values and the increment; these are not meaningful unless
379 /// either NoSignedWrap or NoUnsignedWrap is true, and are always meaningful
380 /// in that case, although the final value may be 0 indicating a nonconstant.
381 ///
382 /// TODO: This duplicates a fair amount of ScalarEvolution logic.
383 /// Perhaps this can be merged with
384 /// ScalarEvolution::getBackedgeTakenCount
385 /// and/or ScalarEvolution::get{Sign,Zero}ExtendExpr.
386 ///
387 static const PHINode *TestOrigIVForWrap(const Loop *L,
388                                         const BranchInst *BI,
389                                         const Instruction *OrigCond,
390                                         const ScalarEvolution &SE,
391                                         bool &NoSignedWrap,
392                                         bool &NoUnsignedWrap,
393                                         const ConstantInt* &InitialVal,
394                                         const ConstantInt* &IncrVal,
395                                         const ConstantInt* &LimitVal) {
396   // Verify that the loop is sane and find the exit condition.
397   const ICmpInst *Cmp = dyn_cast<ICmpInst>(OrigCond);
398   if (!Cmp) return 0;
399
400   const Value *CmpLHS = Cmp->getOperand(0);
401   const Value *CmpRHS = Cmp->getOperand(1);
402   const BasicBlock *TrueBB = BI->getSuccessor(0);
403   const BasicBlock *FalseBB = BI->getSuccessor(1);
404   ICmpInst::Predicate Pred = Cmp->getPredicate();
405
406   // Canonicalize a constant to the RHS.
407   if (isa<ConstantInt>(CmpLHS)) {
408     Pred = ICmpInst::getSwappedPredicate(Pred);
409     std::swap(CmpLHS, CmpRHS);
410   }
411   // Canonicalize SLE to SLT.
412   if (Pred == ICmpInst::ICMP_SLE)
413     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
414       if (!CI->getValue().isMaxSignedValue()) {
415         CmpRHS = ConstantInt::get(CI->getValue() + 1);
416         Pred = ICmpInst::ICMP_SLT;
417       }
418   // Canonicalize SGT to SGE.
419   if (Pred == ICmpInst::ICMP_SGT)
420     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
421       if (!CI->getValue().isMaxSignedValue()) {
422         CmpRHS = ConstantInt::get(CI->getValue() + 1);
423         Pred = ICmpInst::ICMP_SGE;
424       }
425   // Canonicalize SGE to SLT.
426   if (Pred == ICmpInst::ICMP_SGE) {
427     std::swap(TrueBB, FalseBB);
428     Pred = ICmpInst::ICMP_SLT;
429   }
430   // Canonicalize ULE to ULT.
431   if (Pred == ICmpInst::ICMP_ULE)
432     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
433       if (!CI->getValue().isMaxValue()) {
434         CmpRHS = ConstantInt::get(CI->getValue() + 1);
435         Pred = ICmpInst::ICMP_ULT;
436       }
437   // Canonicalize UGT to UGE.
438   if (Pred == ICmpInst::ICMP_UGT)
439     if (const ConstantInt *CI = dyn_cast<ConstantInt>(CmpRHS))
440       if (!CI->getValue().isMaxValue()) {
441         CmpRHS = ConstantInt::get(CI->getValue() + 1);
442         Pred = ICmpInst::ICMP_UGE;
443       }
444   // Canonicalize UGE to ULT.
445   if (Pred == ICmpInst::ICMP_UGE) {
446     std::swap(TrueBB, FalseBB);
447     Pred = ICmpInst::ICMP_ULT;
448   }
449   // For now, analyze only LT loops for signed overflow.
450   if (Pred != ICmpInst::ICMP_SLT && Pred != ICmpInst::ICMP_ULT)
451     return 0;
452
453   bool isSigned = Pred == ICmpInst::ICMP_SLT;
454
455   // Get the increment instruction. Look past casts if we will
456   // be able to prove that the original induction variable doesn't
457   // undergo signed or unsigned overflow, respectively.
458   const Value *IncrInst = CmpLHS;
459   if (isSigned) {
460     if (const SExtInst *SI = dyn_cast<SExtInst>(CmpLHS)) {
461       if (!isa<ConstantInt>(CmpRHS) ||
462           !cast<ConstantInt>(CmpRHS)->getValue()
463             .isSignedIntN(SE.getTypeSizeInBits(IncrInst->getType())))
464         return 0;
465       IncrInst = SI->getOperand(0);
466     }
467   } else {
468     if (const ZExtInst *ZI = dyn_cast<ZExtInst>(CmpLHS)) {
469       if (!isa<ConstantInt>(CmpRHS) ||
470           !cast<ConstantInt>(CmpRHS)->getValue()
471             .isIntN(SE.getTypeSizeInBits(IncrInst->getType())))
472         return 0;
473       IncrInst = ZI->getOperand(0);
474     }
475   }
476
477   // For now, only analyze induction variables that have simple increments.
478   const BinaryOperator *IncrOp = dyn_cast<BinaryOperator>(IncrInst);
479   if (!IncrOp || IncrOp->getOpcode() != Instruction::Add)
480     return 0;
481   IncrVal = dyn_cast<ConstantInt>(IncrOp->getOperand(1));
482   if (!IncrVal)
483     return 0;
484
485   // Make sure the PHI looks like a normal IV.
486   const PHINode *PN = dyn_cast<PHINode>(IncrOp->getOperand(0));
487   if (!PN || PN->getNumIncomingValues() != 2)
488     return 0;
489   unsigned IncomingEdge = L->contains(PN->getIncomingBlock(0));
490   unsigned BackEdge = !IncomingEdge;
491   if (!L->contains(PN->getIncomingBlock(BackEdge)) ||
492       PN->getIncomingValue(BackEdge) != IncrOp)
493     return 0;
494   if (!L->contains(TrueBB))
495     return 0;
496
497   // For now, only analyze loops with a constant start value, so that
498   // we can easily determine if the start value is not a maximum value
499   // which would wrap on the first iteration.
500   InitialVal = dyn_cast<ConstantInt>(PN->getIncomingValue(IncomingEdge));
501   if (!InitialVal)
502     return 0;
503
504   // The upper limit need not be a constant; we'll check later.
505   LimitVal = dyn_cast<ConstantInt>(CmpRHS);
506
507   // We detect the impossibility of wrapping in two cases, both of
508   // which require starting with a non-max value:
509   // - The IV counts up by one, and the loop iterates only while it remains
510   // less than a limiting value (any) in the same type.
511   // - The IV counts up by a positive increment other than 1, and the
512   // constant limiting value + the increment is less than the max value
513   // (computed as max-increment to avoid overflow)
514   if (isSigned && !InitialVal->getValue().isMaxSignedValue()) {
515     if (IncrVal->equalsInt(1))
516       NoSignedWrap = true;    // LimitVal need not be constant
517     else if (LimitVal) {
518       uint64_t numBits = LimitVal->getValue().getBitWidth();
519       if (IncrVal->getValue().sgt(APInt::getNullValue(numBits)) &&
520           (APInt::getSignedMaxValue(numBits) - IncrVal->getValue())
521             .sgt(LimitVal->getValue()))
522         NoSignedWrap = true;
523     }
524   } else if (!isSigned && !InitialVal->getValue().isMaxValue()) {
525     if (IncrVal->equalsInt(1))
526       NoUnsignedWrap = true;  // LimitVal need not be constant
527     else if (LimitVal) {
528       uint64_t numBits = LimitVal->getValue().getBitWidth();
529       if (IncrVal->getValue().ugt(APInt::getNullValue(numBits)) &&
530           (APInt::getMaxValue(numBits) - IncrVal->getValue())
531             .ugt(LimitVal->getValue()))
532         NoUnsignedWrap = true;
533     }
534   }
535   return PN;
536 }
537
538 static Value *getSignExtendedTruncVar(const SCEVAddRecExpr *AR,
539                                       ScalarEvolution *SE,
540                                       const Type *LargestType, Loop *L, 
541                                       const Type *myType,
542                                       SCEVExpander &Rewriter) {
543   SCEVHandle ExtendedStart =
544     SE->getSignExtendExpr(AR->getStart(), LargestType);
545   SCEVHandle ExtendedStep =
546     SE->getSignExtendExpr(AR->getStepRecurrence(*SE), LargestType);
547   SCEVHandle ExtendedAddRec =
548     SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
549   if (LargestType != myType)
550     ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
551   return Rewriter.expandCodeFor(ExtendedAddRec, myType);
552 }
553
554 static Value *getZeroExtendedTruncVar(const SCEVAddRecExpr *AR,
555                                       ScalarEvolution *SE,
556                                       const Type *LargestType, Loop *L, 
557                                       const Type *myType,
558                                       SCEVExpander &Rewriter) {
559   SCEVHandle ExtendedStart =
560     SE->getZeroExtendExpr(AR->getStart(), LargestType);
561   SCEVHandle ExtendedStep =
562     SE->getZeroExtendExpr(AR->getStepRecurrence(*SE), LargestType);
563   SCEVHandle ExtendedAddRec =
564     SE->getAddRecExpr(ExtendedStart, ExtendedStep, L);
565   if (LargestType != myType)
566     ExtendedAddRec = SE->getTruncateExpr(ExtendedAddRec, myType);
567   return Rewriter.expandCodeFor(ExtendedAddRec, myType);
568 }
569
570 /// allUsesAreSameTyped - See whether all Uses of I are instructions
571 /// with the same Opcode and the same type.
572 static bool allUsesAreSameTyped(unsigned int Opcode, Instruction *I) {
573   const Type* firstType = NULL;
574   for (Value::use_iterator UI = I->use_begin(), UE = I->use_end();
575        UI != UE; ++UI) {
576     Instruction *II = dyn_cast<Instruction>(*UI);
577     if (!II || II->getOpcode() != Opcode)
578       return false;
579     if (!firstType)
580       firstType = II->getType();
581     else if (firstType != II->getType())
582       return false;
583   }
584   return true;
585 }
586
587 bool IndVarSimplify::runOnLoop(Loop *L, LPPassManager &LPM) {
588   LI = &getAnalysis<LoopInfo>();
589   SE = &getAnalysis<ScalarEvolution>();
590   Changed = false;
591
592   // If there are any floating-point recurrences, attempt to
593   // transform them to use integer recurrences.
594   RewriteNonIntegerIVs(L);
595
596   BasicBlock *Header       = L->getHeader();
597   BasicBlock *ExitingBlock = L->getExitingBlock();
598   SmallPtrSet<Instruction*, 16> DeadInsts;
599
600   // Verify the input to the pass in already in LCSSA form.
601   assert(L->isLCSSAForm());
602
603   // Check to see if this loop has a computable loop-invariant execution count.
604   // If so, this means that we can compute the final value of any expressions
605   // that are recurrent in the loop, and substitute the exit values from the
606   // loop into any instructions outside of the loop that use the final values of
607   // the current expressions.
608   //
609   SCEVHandle BackedgeTakenCount = SE->getBackedgeTakenCount(L);
610   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount))
611     RewriteLoopExitValues(L, BackedgeTakenCount);
612
613   // Next, analyze all of the induction variables in the loop, canonicalizing
614   // auxillary induction variables.
615   std::vector<std::pair<PHINode*, SCEVHandle> > IndVars;
616
617   for (BasicBlock::iterator I = Header->begin(); isa<PHINode>(I); ++I) {
618     PHINode *PN = cast<PHINode>(I);
619     if (SE->isSCEVable(PN->getType())) {
620       SCEVHandle SCEV = SE->getSCEV(PN);
621       // FIXME: It is an extremely bad idea to indvar substitute anything more
622       // complex than affine induction variables.  Doing so will put expensive
623       // polynomial evaluations inside of the loop, and the str reduction pass
624       // currently can only reduce affine polynomials.  For now just disable
625       // indvar subst on anything more complex than an affine addrec.
626       if (const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(SCEV))
627         if (AR->getLoop() == L && AR->isAffine())
628           IndVars.push_back(std::make_pair(PN, SCEV));
629     }
630   }
631
632   // Compute the type of the largest recurrence expression, and collect
633   // the set of the types of the other recurrence expressions.
634   const Type *LargestType = 0;
635   SmallSetVector<const Type *, 4> SizesToInsert;
636   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount)) {
637     LargestType = BackedgeTakenCount->getType();
638     LargestType = SE->getEffectiveSCEVType(LargestType);
639     SizesToInsert.insert(LargestType);
640   }
641   for (unsigned i = 0, e = IndVars.size(); i != e; ++i) {
642     const PHINode *PN = IndVars[i].first;
643     const Type *PNTy = PN->getType();
644     PNTy = SE->getEffectiveSCEVType(PNTy);
645     SizesToInsert.insert(PNTy);
646     const Type *EffTy = getEffectiveIndvarType(PN, SE);
647     EffTy = SE->getEffectiveSCEVType(EffTy);
648     SizesToInsert.insert(EffTy);
649     if (!LargestType ||
650         SE->getTypeSizeInBits(EffTy) >
651           SE->getTypeSizeInBits(LargestType))
652       LargestType = EffTy;
653   }
654
655   // Create a rewriter object which we'll use to transform the code with.
656   SCEVExpander Rewriter(*SE, *LI);
657
658   // Now that we know the largest of of the induction variables in this loop,
659   // insert a canonical induction variable of the largest size.
660   Value *IndVar = 0;
661   if (!SizesToInsert.empty()) {
662     IndVar = Rewriter.getOrInsertCanonicalInductionVariable(L,LargestType);
663     ++NumInserted;
664     Changed = true;
665     DOUT << "INDVARS: New CanIV: " << *IndVar;
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   bool NoSignedWrap = false;
671   bool NoUnsignedWrap = false;
672   const ConstantInt* InitialVal, * IncrVal, * LimitVal;
673   const PHINode *OrigControllingPHI = 0;
674   if (!isa<SCEVCouldNotCompute>(BackedgeTakenCount) && ExitingBlock)
675     // Can't rewrite non-branch yet.
676     if (BranchInst *BI = dyn_cast<BranchInst>(ExitingBlock->getTerminator())) {
677       if (Instruction *OrigCond = dyn_cast<Instruction>(BI->getCondition())) {
678         // Determine if the OrigIV will ever undergo overflow.
679         OrigControllingPHI =
680           TestOrigIVForWrap(L, BI, OrigCond, *SE,
681                             NoSignedWrap, NoUnsignedWrap,
682                             InitialVal, IncrVal, LimitVal);
683
684         // We'll be replacing the original condition, so it'll be dead.
685         DeadInsts.insert(OrigCond);
686       }
687
688       LinearFunctionTestReplace(L, BackedgeTakenCount, IndVar,
689                                 ExitingBlock, BI, Rewriter);
690     }
691
692   // Now that we have a canonical induction variable, we can rewrite any
693   // recurrences in terms of the induction variable.  Start with the auxillary
694   // induction variables, and recursively rewrite any of their uses.
695   BasicBlock::iterator InsertPt = Header->getFirstNonPHI();
696   Rewriter.setInsertionPoint(InsertPt);
697
698   // If there were induction variables of other sizes, cast the primary
699   // induction variable to the right size for them, avoiding the need for the
700   // code evaluation methods to insert induction variables of different sizes.
701   for (unsigned i = 0, e = SizesToInsert.size(); i != e; ++i) {
702     const Type *Ty = SizesToInsert[i];
703     if (Ty != LargestType) {
704       Instruction *New = new TruncInst(IndVar, Ty, "indvar", InsertPt);
705       Rewriter.addInsertedValue(New, SE->getSCEV(New));
706       DOUT << "INDVARS: Made trunc IV for type " << *Ty << ": "
707            << *New << "\n";
708     }
709   }
710
711   // Rewrite all induction variables in terms of the canonical induction
712   // variable.
713   while (!IndVars.empty()) {
714     PHINode *PN = IndVars.back().first;
715     const SCEVAddRecExpr *AR = cast<SCEVAddRecExpr>(IndVars.back().second);
716     Value *NewVal = Rewriter.expandCodeFor(AR, PN->getType());
717     DOUT << "INDVARS: Rewrote IV '" << *AR << "' " << *PN
718          << "   into = " << *NewVal << "\n";
719     NewVal->takeName(PN);
720
721     /// If the new canonical induction variable is wider than the original,
722     /// and the original has uses that are casts to wider types, see if the
723     /// truncate and extend can be omitted.
724     if (PN == OrigControllingPHI && PN->getType() != LargestType)
725       for (Value::use_iterator UI = PN->use_begin(), UE = PN->use_end();
726            UI != UE; ++UI) {
727         Instruction *UInst = dyn_cast<Instruction>(*UI);
728         if (UInst && isa<SExtInst>(UInst) && NoSignedWrap) {
729           Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType, L, 
730                                          UInst->getType(), Rewriter);
731           UInst->replaceAllUsesWith(TruncIndVar);
732           DeadInsts.insert(UInst);
733         }
734         // See if we can figure out sext(i+constant) doesn't wrap, so we can
735         // use a larger add.  This is common in subscripting.
736         if (UInst && UInst->getOpcode()==Instruction::Add &&
737             !UInst->use_empty() &&
738             allUsesAreSameTyped(Instruction::SExt, UInst) &&
739             isa<ConstantInt>(UInst->getOperand(1)) &&
740             NoSignedWrap && LimitVal) {
741           uint64_t oldBitSize = LimitVal->getValue().getBitWidth();
742           uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
743           ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
744           if (((APInt::getSignedMaxValue(oldBitSize) - IncrVal->getValue()) -
745                 AddRHS->getValue()).sgt(LimitVal->getValue())) {
746             // We've determined this is (i+constant) and it won't overflow.
747             if (isa<SExtInst>(UInst->use_begin())) {
748               SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
749               uint64_t truncSize = oldSext->getType()->getPrimitiveSizeInBits();
750               Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
751                                                 L, oldSext->getType(), Rewriter);
752               APInt APnewAddRHS = APInt(AddRHS->getValue()).sext(newBitSize);
753               if (newBitSize > truncSize)
754                 APnewAddRHS = APnewAddRHS.trunc(truncSize);
755               ConstantInt* newAddRHS =ConstantInt::get(APnewAddRHS);
756               Value *NewAdd = 
757                     BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
758                                               UInst->getName()+".nosex", UInst);
759               for (Value::use_iterator UI2 = UInst->use_begin(), 
760                     UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
761                 Instruction *II = dyn_cast<Instruction>(UI2);
762                 II->replaceAllUsesWith(NewAdd);
763                 DeadInsts.insert(II);
764               }
765               DeadInsts.insert(UInst);
766             }
767           }
768         }
769         // Try for sext(i | constant).  This is safe as long as the
770         // high bit of the constant is not set.
771         if (UInst && UInst->getOpcode()==Instruction::Or &&
772             !UInst->use_empty() &&
773             allUsesAreSameTyped(Instruction::SExt, UInst) && NoSignedWrap &&
774             isa<ConstantInt>(UInst->getOperand(1))) {
775           ConstantInt* RHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
776           if (!RHS->getValue().isNegative()) {
777             uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
778             SExtInst* oldSext = dyn_cast<SExtInst>(UInst->use_begin());
779             uint64_t truncSize = oldSext->getType()->getPrimitiveSizeInBits();
780             Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
781                                               L, oldSext->getType(), Rewriter);
782             APInt APnewOrRHS = APInt(RHS->getValue()).sext(newBitSize);
783             if (newBitSize > truncSize)
784               APnewOrRHS = APnewOrRHS.trunc(truncSize);
785             ConstantInt* newOrRHS =ConstantInt::get(APnewOrRHS);
786             Value *NewOr = 
787                   BinaryOperator::CreateOr(TruncIndVar, newOrRHS,
788                                             UInst->getName()+".nosex", UInst);
789             for (Value::use_iterator UI2 = UInst->use_begin(), 
790                   UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
791               Instruction *II = dyn_cast<Instruction>(UI2);
792               II->replaceAllUsesWith(NewOr);
793               DeadInsts.insert(II);
794             }
795             DeadInsts.insert(UInst);
796           }
797         }
798         // A zext of a signed variable known not to overflow is still safe.
799         if (UInst && isa<ZExtInst>(UInst) && (NoUnsignedWrap || NoSignedWrap)) {
800           Value *TruncIndVar = getZeroExtendedTruncVar(AR, SE, LargestType, L, 
801                                          UInst->getType(), Rewriter);
802           UInst->replaceAllUsesWith(TruncIndVar);
803           DeadInsts.insert(UInst);
804         }
805         // If we have zext(i&constant), it's always safe to use the larger
806         // variable.  This is not common but is a bottleneck in Openssl.
807         // (RHS doesn't have to be constant.  There should be a better approach
808         // than bottom-up pattern matching for this...)
809         if (UInst && UInst->getOpcode()==Instruction::And &&
810             !UInst->use_empty() &&
811             allUsesAreSameTyped(Instruction::ZExt, UInst) &&
812             isa<ConstantInt>(UInst->getOperand(1))) {
813           uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
814           ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
815           ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst->use_begin());
816           uint64_t truncSize = oldZext->getType()->getPrimitiveSizeInBits();
817           Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
818                                   L, oldZext->getType(), Rewriter);
819           APInt APnewAndRHS = APInt(AndRHS->getValue()).zext(newBitSize);
820           if (newBitSize > truncSize)
821             APnewAndRHS = APnewAndRHS.trunc(truncSize);
822           ConstantInt* newAndRHS = ConstantInt::get(APnewAndRHS);
823           Value *NewAnd = 
824                 BinaryOperator::CreateAnd(TruncIndVar, newAndRHS,
825                                           UInst->getName()+".nozex", UInst);
826           for (Value::use_iterator UI2 = UInst->use_begin(), 
827                 UE2 = UInst->use_end(); UI2 != UE2; ++UI2) {
828             Instruction *II = dyn_cast<Instruction>(UI2);
829             II->replaceAllUsesWith(NewAnd);
830             DeadInsts.insert(II);
831           }
832           DeadInsts.insert(UInst);
833         }
834         // If we have zext((i+constant)&constant), we can use the larger
835         // variable even if the add does overflow.  This works whenever the
836         // constant being ANDed is the same size as i, which it presumably is.
837         // We don't need to restrict the expression being and'ed to i+const,
838         // but we have to promote everything in it, so it's convenient.
839         // zext((i | constant)&constant) is also valid and accepted here.
840         if (UInst && (UInst->getOpcode()==Instruction::Add ||
841                       UInst->getOpcode()==Instruction::Or) &&
842             UInst->hasOneUse() &&
843             isa<ConstantInt>(UInst->getOperand(1))) {
844           uint64_t newBitSize = LargestType->getPrimitiveSizeInBits();
845           ConstantInt* AddRHS = dyn_cast<ConstantInt>(UInst->getOperand(1));
846           Instruction *UInst2 = dyn_cast<Instruction>(UInst->use_begin());
847           if (UInst2 && UInst2->getOpcode() == Instruction::And &&
848               !UInst2->use_empty() &&
849               allUsesAreSameTyped(Instruction::ZExt, UInst2) &&
850               isa<ConstantInt>(UInst2->getOperand(1))) {
851             ZExtInst* oldZext = dyn_cast<ZExtInst>(UInst2->use_begin());
852             uint64_t truncSize = oldZext->getType()->getPrimitiveSizeInBits();
853             Value *TruncIndVar = getSignExtendedTruncVar(AR, SE, LargestType,
854                                     L, oldZext->getType(), Rewriter);
855             ConstantInt* AndRHS = dyn_cast<ConstantInt>(UInst2->getOperand(1));
856             APInt APnewAddRHS = APInt(AddRHS->getValue()).zext(newBitSize);
857             if (newBitSize > truncSize)
858               APnewAddRHS = APnewAddRHS.trunc(truncSize);
859             ConstantInt* newAddRHS = ConstantInt::get(APnewAddRHS);
860             Value *NewAdd = ((UInst->getOpcode()==Instruction::Add) ?
861                   BinaryOperator::CreateAdd(TruncIndVar, newAddRHS,
862                                             UInst->getName()+".nozex", UInst2) :
863                   BinaryOperator::CreateOr(TruncIndVar, newAddRHS,
864                                             UInst->getName()+".nozex", UInst2));
865             APInt APcopy2 = APInt(AndRHS->getValue());
866             ConstantInt* newAndRHS = ConstantInt::get(APcopy2.zext(newBitSize));
867             Value *NewAnd = 
868                   BinaryOperator::CreateAnd(NewAdd, newAndRHS,
869                                             UInst->getName()+".nozex", UInst2);
870             for (Value::use_iterator UI2 = UInst2->use_begin(), 
871                   UE2 = UInst2->use_end(); UI2 != UE2; ++UI2) {
872               Instruction *II = dyn_cast<Instruction>(UI2);
873               II->replaceAllUsesWith(NewAnd);
874               DeadInsts.insert(II);
875             }
876             DeadInsts.insert(UInst);
877             DeadInsts.insert(UInst2);
878           }
879         }
880       }
881
882     // Replace the old PHI Node with the inserted computation.
883     PN->replaceAllUsesWith(NewVal);
884     DeadInsts.insert(PN);
885     IndVars.pop_back();
886     ++NumRemoved;
887     Changed = true;
888   }
889
890   DeleteTriviallyDeadInstructions(DeadInsts);
891   assert(L->isLCSSAForm());
892   return Changed;
893 }
894
895 /// Return true if it is OK to use SIToFPInst for an inducation variable
896 /// with given inital and exit values.
897 static bool useSIToFPInst(ConstantFP &InitV, ConstantFP &ExitV,
898                           uint64_t intIV, uint64_t intEV) {
899
900   if (InitV.getValueAPF().isNegative() || ExitV.getValueAPF().isNegative())
901     return true;
902
903   // If the iteration range can be handled by SIToFPInst then use it.
904   APInt Max = APInt::getSignedMaxValue(32);
905   if (Max.getZExtValue() > static_cast<uint64_t>(abs(intEV - intIV)))
906     return true;
907
908   return false;
909 }
910
911 /// convertToInt - Convert APF to an integer, if possible.
912 static bool convertToInt(const APFloat &APF, uint64_t *intVal) {
913
914   bool isExact = false;
915   if (&APF.getSemantics() == &APFloat::PPCDoubleDouble)
916     return false;
917   if (APF.convertToInteger(intVal, 32, APF.isNegative(),
918                            APFloat::rmTowardZero, &isExact)
919       != APFloat::opOK)
920     return false;
921   if (!isExact)
922     return false;
923   return true;
924
925 }
926
927 /// HandleFloatingPointIV - If the loop has floating induction variable
928 /// then insert corresponding integer induction variable if possible.
929 /// For example,
930 /// for(double i = 0; i < 10000; ++i)
931 ///   bar(i)
932 /// is converted into
933 /// for(int i = 0; i < 10000; ++i)
934 ///   bar((double)i);
935 ///
936 void IndVarSimplify::HandleFloatingPointIV(Loop *L, PHINode *PH,
937                                    SmallPtrSet<Instruction*, 16> &DeadInsts) {
938
939   unsigned IncomingEdge = L->contains(PH->getIncomingBlock(0));
940   unsigned BackEdge     = IncomingEdge^1;
941
942   // Check incoming value.
943   ConstantFP *InitValue = dyn_cast<ConstantFP>(PH->getIncomingValue(IncomingEdge));
944   if (!InitValue) return;
945   uint64_t newInitValue = Type::Int32Ty->getPrimitiveSizeInBits();
946   if (!convertToInt(InitValue->getValueAPF(), &newInitValue))
947     return;
948
949   // Check IV increment. Reject this PH if increement operation is not
950   // an add or increment value can not be represented by an integer.
951   BinaryOperator *Incr =
952     dyn_cast<BinaryOperator>(PH->getIncomingValue(BackEdge));
953   if (!Incr) return;
954   if (Incr->getOpcode() != Instruction::Add) return;
955   ConstantFP *IncrValue = NULL;
956   unsigned IncrVIndex = 1;
957   if (Incr->getOperand(1) == PH)
958     IncrVIndex = 0;
959   IncrValue = dyn_cast<ConstantFP>(Incr->getOperand(IncrVIndex));
960   if (!IncrValue) return;
961   uint64_t newIncrValue = Type::Int32Ty->getPrimitiveSizeInBits();
962   if (!convertToInt(IncrValue->getValueAPF(), &newIncrValue))
963     return;
964
965   // Check Incr uses. One user is PH and the other users is exit condition used
966   // by the conditional terminator.
967   Value::use_iterator IncrUse = Incr->use_begin();
968   Instruction *U1 = cast<Instruction>(IncrUse++);
969   if (IncrUse == Incr->use_end()) return;
970   Instruction *U2 = cast<Instruction>(IncrUse++);
971   if (IncrUse != Incr->use_end()) return;
972
973   // Find exit condition.
974   FCmpInst *EC = dyn_cast<FCmpInst>(U1);
975   if (!EC)
976     EC = dyn_cast<FCmpInst>(U2);
977   if (!EC) return;
978
979   if (BranchInst *BI = dyn_cast<BranchInst>(EC->getParent()->getTerminator())) {
980     if (!BI->isConditional()) return;
981     if (BI->getCondition() != EC) return;
982   }
983
984   // Find exit value. If exit value can not be represented as an interger then
985   // do not handle this floating point PH.
986   ConstantFP *EV = NULL;
987   unsigned EVIndex = 1;
988   if (EC->getOperand(1) == Incr)
989     EVIndex = 0;
990   EV = dyn_cast<ConstantFP>(EC->getOperand(EVIndex));
991   if (!EV) return;
992   uint64_t intEV = Type::Int32Ty->getPrimitiveSizeInBits();
993   if (!convertToInt(EV->getValueAPF(), &intEV))
994     return;
995
996   // Find new predicate for integer comparison.
997   CmpInst::Predicate NewPred = CmpInst::BAD_ICMP_PREDICATE;
998   switch (EC->getPredicate()) {
999   case CmpInst::FCMP_OEQ:
1000   case CmpInst::FCMP_UEQ:
1001     NewPred = CmpInst::ICMP_EQ;
1002     break;
1003   case CmpInst::FCMP_OGT:
1004   case CmpInst::FCMP_UGT:
1005     NewPred = CmpInst::ICMP_UGT;
1006     break;
1007   case CmpInst::FCMP_OGE:
1008   case CmpInst::FCMP_UGE:
1009     NewPred = CmpInst::ICMP_UGE;
1010     break;
1011   case CmpInst::FCMP_OLT:
1012   case CmpInst::FCMP_ULT:
1013     NewPred = CmpInst::ICMP_ULT;
1014     break;
1015   case CmpInst::FCMP_OLE:
1016   case CmpInst::FCMP_ULE:
1017     NewPred = CmpInst::ICMP_ULE;
1018     break;
1019   default:
1020     break;
1021   }
1022   if (NewPred == CmpInst::BAD_ICMP_PREDICATE) return;
1023
1024   // Insert new integer induction variable.
1025   PHINode *NewPHI = PHINode::Create(Type::Int32Ty,
1026                                     PH->getName()+".int", PH);
1027   NewPHI->addIncoming(ConstantInt::get(Type::Int32Ty, newInitValue),
1028                       PH->getIncomingBlock(IncomingEdge));
1029
1030   Value *NewAdd = BinaryOperator::CreateAdd(NewPHI,
1031                                             ConstantInt::get(Type::Int32Ty,
1032                                                              newIncrValue),
1033                                             Incr->getName()+".int", Incr);
1034   NewPHI->addIncoming(NewAdd, PH->getIncomingBlock(BackEdge));
1035
1036   // The back edge is edge 1 of newPHI, whatever it may have been in the
1037   // original PHI.
1038   ConstantInt *NewEV = ConstantInt::get(Type::Int32Ty, intEV);
1039   Value *LHS = (EVIndex == 1 ? NewPHI->getIncomingValue(1) : NewEV);
1040   Value *RHS = (EVIndex == 1 ? NewEV : NewPHI->getIncomingValue(1));
1041   ICmpInst *NewEC = new ICmpInst(NewPred, LHS, RHS, EC->getNameStart(),
1042                                  EC->getParent()->getTerminator());
1043
1044   // Delete old, floating point, exit comparision instruction.
1045   EC->replaceAllUsesWith(NewEC);
1046   DeadInsts.insert(EC);
1047
1048   // Delete old, floating point, increment instruction.
1049   Incr->replaceAllUsesWith(UndefValue::get(Incr->getType()));
1050   DeadInsts.insert(Incr);
1051
1052   // Replace floating induction variable. Give SIToFPInst preference over
1053   // UIToFPInst because it is faster on platforms that are widely used.
1054   if (useSIToFPInst(*InitValue, *EV, newInitValue, intEV)) {
1055     SIToFPInst *Conv = new SIToFPInst(NewPHI, PH->getType(), "indvar.conv",
1056                                       PH->getParent()->getFirstNonPHI());
1057     PH->replaceAllUsesWith(Conv);
1058   } else {
1059     UIToFPInst *Conv = new UIToFPInst(NewPHI, PH->getType(), "indvar.conv",
1060                                       PH->getParent()->getFirstNonPHI());
1061     PH->replaceAllUsesWith(Conv);
1062   }
1063   DeadInsts.insert(PH);
1064 }
1065